为什么我的选择器在SwiftUI中没有响应?

问题描述 投票:0回答:3

我曾尝试在分段式和轮式捡拾器之间切换,但是在单击时都未注册选择。

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
3个回答
0
投票

向每个选择器项目添加标签,使其具有唯一性,例如

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

0
投票

再次检查settings.senatorChoice是否为IntForEach中范围的类型必须与Picker绑定的类型相匹配。 (有关更多信息,请参见here。)>

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

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

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])")
        }
    }
}
}

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.