SwiftUI分段选择器默认状态为nil

问题描述

我正在使用一种形式的分段选择器来回答简单的“是”和“否”问题。可以将分段选择器的初始状态设置为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()
            }
        }
    }
}

解决方法

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

例如:

@State private var equipmentCheck = -1

有效。

我正在寻找可以确保可以正常工作但没有找到工作的文档。

UIKit UISegmentedControl的{​​{3}}的文档说将值设置为-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()
            }
        }
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...