【问题标题】:Why is my picker unresponsive in SwiftUI?为什么我的选择器在 SwiftUI 中没有响应?
【发布时间】:2020-06-13 20:36:49
【问题描述】:

我尝试在分段选择器和滚轮选择器之间切换,但在单击时都没有注册选择。

NavigationView {
    Form {
        Picker(selection: self.$settings.senatorChoice, label: Text("Choose a senator")) {
            ForEach(0 ..< self.customSenators.count) {
                Text(self.customSenators[$0])
            }
        }.pickerStyle(WheelPickerStyle())
        .labelsHidden()
        .padding()
    }
}

【问题讨论】:

    标签: swift swiftui picker navigationview swiftui-picker


    【解决方案1】:

    仔细检查settings.senatorChoiceIntForEach 中的范围类型必须与 Picker 的绑定类型匹配。 (请参阅here 了解更多信息)。

    此外,您可能还想使用ForEach(self.customSenators.indices, id: \.self)。如果元素被添加到customSenators 或从customSenators 删除,这可以防止可能的崩溃和过时的 UI。 (有关更多信息,请参阅here。)

    【讨论】:

      【解决方案2】:

      为每个选择器项目添加一个标签,以便它们是唯一的,例如

      Text(self.customSenators[$0]).tag($0)
      

      【讨论】:

        【解决方案3】:

        以下测试代码在单击时注册选择。

        struct Settings {
           var senatorChoice: Int = 0
        }
        
        struct ContentView: View {
        @State private var settings = Settings()
        @State private var customSenators = ["One","Two","Three"]
        
        var body: some View {
            NavigationView {
                Form {
                    Picker(selection: self.$settings.senatorChoice, label: Text("Choose a senator")) {
                        ForEach(0 ..< customSenators.count) {
                            Text(self.customSenators[$0])
                        }
                    }.pickerStyle(SegmentedPickerStyle())
                        .labelsHidden()
                        .padding()
                    Text("value: \(customSenators[settings.senatorChoice])")
                }
            }
        }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-07
          • 2015-12-30
          • 2014-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多