Swiftui 更换选择器';动态更新内容
我想动态更改选择器的内容。Swiftui 更换选择器';动态更新内容,swiftui,Swiftui,我想动态更改选择器的内容。 但我认为不能将绑定属性传递给ForEach @Binding var options: [String] @Binding var selectedIndex: Int var body: some View { Picker(selection: self.$selectedIndex, label: Text("")) { ForEach(0..<self.$options.count) { // error: Cannot ass
但我认为不能将绑定属性传递给ForEach
@Binding var options: [String]
@Binding var selectedIndex: Int
var body: some View {
Picker(selection: self.$selectedIndex, label: Text("")) {
ForEach(0..<self.$options.count) { // error: Cannot assign to property: 'count' is a get-only property
Text(self.options[$0])
}
}
}
@绑定变量选项:[字符串]
@绑定变量selectedIndex:Int
var body:一些观点{
选择器(选择:self.$selectedIndex,标签:文本(“”)){
ForEach(0..这里是一个可能解决方案的演示。使用Xcode 11.4/iOS 13.4进行测试
struct TestPickerView: View {
@Binding var options: [String]
@Binding var selectedIndex: Int
var body: some View {
Picker(selection: self.$selectedIndex, label: Text("")) {
ForEach(Array(self.options.enumerated()), id: \.element) { index, item in
Text(item).tag(index)
}
}.id(options) // << important !!
}
}
struct TestPickerView:View{
@绑定变量选项:[字符串]
@绑定变量selectedIndex:Int
var body:一些观点{
选择器(选择:self.$selectedIndex,标签:文本(“”)){
ForEach(数组(self.options.enumerated()),id:\.element){index,中的项
文本(项).标记(索引)
}
}.id(options)//感谢您的大力支持。出现了另一个问题。当我将options定义为[Int]并选择Picker时,Picker将元素本身传递到selectedIndex中,即使set.tag(index)