I have a page view that's calling an array's index to populate the page. When something happens I want to increment the index so it updates the page's content. In this code example, I have this happening upon button press. In my real app, I'll want this to happen when the timer reaches 0 but I suspect that if I can figure out how to get this button press version to work I can extrapolate this to my real use case. Here is the simple code for your review:
import SwiftUI
struct LanguageStruct: Identifiable {
var id = UUID()
var groupTitle: String
var title: String
var subTitle: String
var image: String
}
var progLanguages = [
LanguageStruct(groupTitle: "Java", title: "Lame Langauge", subTitle: "Bad GUI", image: "Push-ups Wide"),
LanguageStruct(groupTitle: "SwiftUI", title: "Nice and New", subTitle: "Better than Swift but incomplete", image: "Sit-ups")
]
struct Playground_arrays: View {
@State private var index = 0
var programming: LanguageStruct
var body: some View {
VStack {
Text(programming.groupTitle)
Text (programming.subTitle)
Image(programming.image)
Button(action:{
//actions go here
if index < 2{
index = 1
}else{
index = 0
}
}, label:{
Text("Change Index")
.fontWeight(.semibold)
})
.buttonStyle(PrimaryButtonStyle(buttonColor: "PositiveGreen"))
}
}
}
struct Playground_arrays_Previews: PreviewProvider {
static var previews: some View {
Playground_arrays(programming: progLanguages[0])
.previewDevice("iPhone 12 mini")
}
}
Can someone please help me figure out how to update the array's index upon button press so I can update the pages content? This seems like it should really be as simple as taking the above index
var counter and placing it in the programing: progLanguages[index]
string or something but I can't for the life of me figure out how to make it work :(
CodePudding user response:
Just have programming
as a dynamic getter:
struct Playground_arrays: View {
@State private var index = 0
var programming: LanguageStruct {
progLanguages[index]
}
var body: some View {
VStack {
Text(programming.groupTitle)
Text (programming.subTitle)
Image(programming.image)
Button(action:{
//actions go here
if index < progLanguages.count - 1 {
index = 1
} else {
index = 0
}
}, label:{
Text("Change Index")
.fontWeight(.semibold)
})
.buttonStyle(PrimaryButtonStyle(buttonColor: "PositiveGreen"))
}
}
}