【问题标题】:SwiftUI segmented picker default state as nilSwiftUI 分段选择器默认状态为 nil
【发布时间】:2020-08-21 08:01:13
【问题描述】:

我在表单中使用分段选择器来回答简单的“是”和“否”问题。分段选择器初始状态是否可以设置为 nil,以便在出现时既不突出显示/选择是或否?

@State private var equipmentCheck = 0
private var answers = ["Yes", "No"]

var body: some View {
    NavigationView {
        Form {
            Section(header: Text("Questions")) {
                Text("Have the plant and equipment been checked?")
                Picker("", selection: $equipmentCheck) {
                    ForEach(0 ..< answers.count, id: \.self) {
                        Text("\(self.answers[$0])")
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding()
            }
        }
    }
}

【问题讨论】:

  • 我对@9​​87654322@ 没有太多经验,但我看到您正在自己设置选择器的标签。为什么不根据equipmentCheck 自定义ForEach 块中的Text。现在,您必须记住,Picker 现在有三个统计信息 - none, yes , no

标签: ios swiftui picker


【解决方案1】:

这是一种可能的方法。使用 Xcode 11.4 / iOS 13.4 测试和使用

@State private var equipmentCheck: Int?        // << here !!
private var answers = ["Yes", "No"]

var body: some View {
    NavigationView {
        Form {
            Section(header: Text("Questions")) {
                Text("Have the plant and equipment been checked?")
                Picker("", selection: $equipmentCheck) {
                    ForEach(0 ..< answers.count, id: \.self) {
                        Text("\(self.answers[$0])")
                           .tag(Optional($0))           // << here !!
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding()
            }
        }
    }
}

【讨论】:

  • 这似乎依赖于相同的机制,即不匹配任何标签的选择将显示未选择的界面。您是否知道任何说明这是官方行为的文档?
【解决方案2】:

似乎如果您将所选值设置为不在分段控件中的索引,则不会突出显示任何值。

例如:

@State private var equipmentCheck = -1

有效。

我正在寻找确认这可以保证工作的文档,但没有找到。

UIKit 的 UISegmentedControlselectedSegmentIndex 的文档说将值设置为 -1 以删除选择,所以在这里这样做似乎也是合理的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多