SwiftUI Picker在使用分组时,在列表中添加了额外的顶部行。

huangapple go评论69阅读模式
英文:

SwiftUI Picker in List adding extra row on top when using sections

问题

I have a SwiftUI inline picker in a list. It works fine; however, when I enclose it in a section, an empty row appears on top of each section with an inline picker. Is there any way to remove this empty row? If I remove the section, the empty row disappears.

英文:

I have a SwiftUI inline picker in a list. It works fine however when I enclose it in a section, an empty row appears on top of each section with an inline picker. Is there anyway to remove this empty row? If I remove the section the empty row disappears.

@State var color: String = "Red"
var colors: [String] = ["Red", "Green", "Blue"]

var body: some View {
    List {
        Section(header: Text("Colors")) {
            Picker("", selection: $color) {
                ForEach(colors, id: \.self) { color in
                    Text(color)
                }
            }
            .pickerStyle(InlinePickerStyle())
        }
    }
}

SwiftUI Picker在使用分组时,在列表中添加了额外的顶部行。

var body: some View {
    List {
        Picker("", selection: $color) {
            ForEach(colors, id: \.self) { color in
                Text(color)
            }
        }
        .pickerStyle(InlinePickerStyle())
    }
}

SwiftUI Picker在使用分组时,在列表中添加了额外的顶部行。

答案1

得分: 1

init(selection:content:label:)中的init更改为空标签即可解决问题。

Section("颜色") {
    Picker(selection: $color) {
        ForEach(colors, id: \.self) { color in
            Text(color)
        }
    } label: {}
    .pickerStyle(.inline)
}

或者如@workingdogsupportUkraine在评论中提到的,您也可以使用修饰符`.labelsHidden()`

Section(header: Text("颜色")) {
    Picker("Picker", selection: $color) {
        ForEach(colors, id: \.self) { color in
            Text(color)
        }
    }
    .pickerStyle(InlinePickerStyle())
    .labelsHidden()
}
英文:

Changing the init to init(selection:content:label:) with an empty label fixes the issue

Section("Colors") {
    Picker(selection: $color) {
        ForEach(colors, id: \.self) { color in
            Text(color)
        }
    } label: {}
    .pickerStyle(.inline)
}

or as mentioned in the comments by @workingdogsupportUkraine you can also use the modifier .labelsHidden()

Section(header: Text("Colors")) {
    Picker("Picker", selection: $color) {
        ForEach(colors, id: \.self) { color in
            Text(color)
        }
    }
    .pickerStyle(InlinePickerStyle())
    .labelsHidden()
}

huangapple
  • 本文由 发表于 2023年5月7日 14:00:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定