我使用Picker选项进行无选择,在iOS15中它工作得很好,但是在iOS16中它有一个默认值,如何删除这个默认值,当选择为零时,我不需要将文本显示在Picker行的右边。
struct ContentView: View {
@State private var selection: String?
let strengths = ["Mild", "Medium", "Mature"]
var body: some View {
NavigationView {
List {
Section {
Picker("Strength", selection: $selection) {
ForEach(strengths, id: \.self) {
Text($0).tag(Optional($0))
}
}
}
}
}
}
}在iOS15中,当选择为零时,不会在选择器行的右侧显示文本。

但是在iOS 16中,相同的代码导致不同的结果,当选择为零时,它有一个默认值。

发布于 2022-09-30 06:36:02
Xcode 14.1 Beta 3日志:"Picker:选择“"nil”无效,并且没有关联的标记,这将提供未定义的结果。
要解决这个日志,您需要添加一个使用nil标记的选项。
struct ContentView: View {
@State private var selection: String?
let strengths = ["Mild", "Medium", "Mature"]
var body: some View {
NavigationView {
List {
Section {
Picker("Strength", selection: $selection) {
Text("No Option").tag(Optional<String>(nil))
ForEach(strengths, id: \.self) {
Text($0).tag(Optional($0))
}
}
Text("current selection: \(selection ?? "none")")
}
}
}
}
}发布于 2022-10-18 18:05:22
这就是我在iOS 14.0.1中为XCode 16.0所做的事情(为了避免用户对iOS 16.0设备感到烦躁):
let promptText: String = "select" // just a default String
//short one for your example
Section {
Picker("Strength", selection: $selection) {
if selection == nil { // this will work, since there is no initialization to the optional value in your example
Text(promptText).tag(Optional<String>(nil)) // is only shown until a selection is made
}
ForEach(strengths, id: \.self) {
Text($0).tag(Optional($0))
}
}
}
// more universal example
Section {
Picker("Strength", selection: $selection) {
if let safeSelection = selection{
if !strengths.contains(safeSelection){ // does not care about a initialization value as long as it is not part of the collection 'strengths'
Text(promptText).tag(Optional<String>(nil)) // is only shown until a selection is made
}
}else{
Text(promptText).tag(Optional<String>(nil))
}
ForEach(strengths, id: \.self) {
Text($0).tag(Optional($0))
}
}
}
// Don't want to see anything if nothing is selected? empty String "" leads to an warning. Go with non visual character like " " or 'Horizontal Tab'. But then you will get an empty row...
Section {
let charHorizontalTab: String = String(Character(UnicodeScalar(9)))
Picker("Strength", selection: $selection) {
if let safeSelection = selection{
if !strengths.contains(safeSelection){ // does not care about a initialization value as long as it is not part of the collection 'strengths'
Text(charHorizontalTab).tag(Optional<String>(nil)) // is only shown until a selection is made
}
}else{
Text(charHorizontalTab).tag(Optional<String>(nil))
}
ForEach(strengths, id: \.self) {
Text($0).tag(Optional($0))
}
}
}祝你好运,找到适合你的解决方案。
https://stackoverflow.com/questions/73903569
复制相似问题