我有两个元素数量不同的数组,并希望在不同的子视图中显示每个元素。因此,用户必须选择“下一步”,然后显示数组的下一个元素,直到他/她在数组的末尾为止。
它应该像这样工作:
---FirstView(FirstElement)---SecondView(SecondElement)---ThirdView(ThirdElement)--Close
Mainview
---FirstView(FirstElement)---SecondView(SecondElement)--Close
所以我需要的视图数是可变的。但是我不知道该怎么办,找不到这样的东西。
我的代码如下
struct ContentView: View {
@State private var showPopover: Bool = false
var body: some View {
Button(action: {
self.showPopover.toggle()
}) {
Text("Choose a Usergroup")
}.sheet(isPresented: $showPopover) {
NewView(showPopover: $showPopover)
}
}
}
struct NewView: View {
@Binding var showPopover: Bool
@State var namesOfFemaleUsers = ["Sabrina", "Nicole", "Barbara"]
@State var namesOfMaleUsers = ["Peter", "Bart", "Homer", "Bernie", "Carl"]
var body: some View {
NavigationView {
HStack {
NavigationLink(
destination: VariableView(showPopover: $showPopover, arrayData: namesOfMaleUsers),
label: {
Text("Male Users")
})
NavigationLink(
destination: VariableView(showPopover: $showPopover, arrayData: namesOfFemaleUsers),
label: {
Text("Female Users")
})
}
}
}
}
struct VariableView: View {
@Binding var showPopover: Bool
@State var arrayData: [String]
var body: some View {
VStack {
// Here should be a Text with the name of first element and a button to go to the next View with the second element
Button(action: {self.showPopover.toggle()}){
Text("Close")
}
}
}
}
答案 0 :(得分:0)
这是一种可行的方法,只需对可用数据的索引进行操作,检查安全范围即可。
通过Xcode 12 / iOS 14测试。
struct NewView: View {
@Binding var showPopover: Bool
var namesOfFemaleUsers = ["Sabrina", "Nicole", "Barbara"]
var namesOfMaleUsers = ["Peter", "Bart", "Homer", "Bernie", "Carl"]
var body: some View {
NavigationView {
HStack {
if !namesOfMaleUsers.isEmpty {
NavigationLink(
destination: VariableView(showPopover: $showPopover, arrayData: namesOfMaleUsers, index: 0),
label: {
Text("Male Users")
})
}
if !namesOfFemaleUsers.isEmpty {
NavigationLink(
destination: VariableView(showPopover: $showPopover, arrayData: namesOfFemaleUsers, index: 0),
label: {
Text("Female Users")
})
}
}
}
}
}
struct VariableView: View {
@Binding var showPopover: Bool
var arrayData: [String]
var index: Int
var body: some View {
VStack {
Text("User: \(arrayData[index])")
if index + 1 < arrayData.count {
NavigationLink(
destination: VariableView(showPopover: $showPopover, arrayData: arrayData, index: index + 1),
label: {
Text("Next")
})
}
Button(action: {self.showPopover.toggle()}){
Text("Close")
}
}
}
}