【问题标题】: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.senatorChoice 是Int。 ForEach 中的范围类型必须与 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])")
}
}
}
}