Search code examples
iosxcodeswiftuiswiftui-listswiftui-picker

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 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())
        }
    }
}

enter image description here

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

enter image description here


Solution

  • 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()
    }