以下代码在运行时每次按下按钮时都会创建新控件,问题是选择器选择设置为相同状态。
如何创建具有不同状态变量的新控件,以便它们可以单独操作?
struct ContentView: View {
@State private var numberOfControlls = 0
@State var selection: String="1"
var body: some View {
VStack {
Button(action: {
self.numberOfControlls += 1
}) {
Text("Tap to add")
}
ForEach(0 ..< numberOfControlls, id: \.self) { _ in
Picker(selection: self.$selection, label:
Text("Picker") {
Text("1").tag(1)
Text("2").tag(2)
}
}
}
}
}
最佳答案
How can I create new controls with different state variables so they can operate separately ?
将控件分离到具有自己状态的独立 View 中(或在需要时查看模型)。
这是一个演示:
struct ContentView: View {
@State private var numberOfControlls = 0
var body: some View {
VStack {
Button(action: {
self.numberOfControlls += 1
}) {
Text("Tap to add")
}
ForEach(0 ..< numberOfControlls, id: \.self) { _ in
ControlView()
}
}
}
}
struct ControlView: View {
@State var selection: String="1"
var body: some View {
Picker(selection: self.$selection, label:
Text("Picker")) {
Text("1").tag(1)
Text("2").tag(2)
}
}
}
关于ios - 在 SwiftUI 中运行时创建控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63448628/