[英]How to change array index in SwiftUI
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.
在我的真实应用程序中,我希望在计时器达到 0 时发生这种情况,但我怀疑如果我能弄清楚如何让这个按钮按下版本工作,我可以将其推断到我的实际用例中。 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 :(这似乎真的应该像采用上述
index
programing: progLanguages[index]
计数器并将其放入programing: progLanguages[index]
一样简单programing: progLanguages[index]
字符串或其他东西,但我一生都无法弄清楚如何使其工作:(
Just have programming
as a dynamic getter:只需将
programming
作为动态吸气剂:
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 < 2{
index += 1
} else {
index = 0
}
}, label:{
Text("Change Index")
.fontWeight(.semibold)
})
.buttonStyle(PrimaryButtonStyle(buttonColor: "PositiveGreen"))
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.