Display segmented Picker in Form without section background & padding

946 views Asked by At

I want to display a picker with segmented style inside a form.

Form {
    Section {
        Picker("Picker", selection: $selectedOption) {
            Text("Option 1")
            Text("Option 2")
        }
        .pickerStyle(.segmented)
    } header: {
        Text("Pick an option")
    }
}

The above code embeds the picker in a section and adds some padding around it (see screenshot). This padding and the white section background looks ugly and is not really needed as the picker already pops out of the background. So I want to get rid of this section background and all the paddings to visually lift the picker to the top level.

Screenshot of Segmented Picker

I found this other Stackoverflow post that suggests to add the following two modifiers to the picker:

.listRowInsets(.init())
.listRowBackground(.secondarySystemBackground) // (I use .clear instead)

That works to a certain extent:

  • The listRowInsets modifier removes the horizontal padding on the left and on the right.

  • The listRowBackground modifier clears the section's background color (or makes it indistinguishable from the form's background).

However, the vertical section padding above and below the picker still remains. To illustrate this, I kept the listRowBackground white:

Picker Screenshot with vertical padding only

When I make it transparent, the section header has too much spacing with respect to the picker, the extra padding is indicated by the red line on top.

Question:

Is there a (clean) way to get rid of this padding (both horizontally and vertically)?

1

There are 1 answers

0
ChrisR On

You cannot get rid of all padding, as the Form cell has a fixed height and the picker is smaller. But you can shift the picker up to correct the distance to the section header (you might have to live with the extra padding below).

either so (seems a litte unclean ;):

     .listRowInsets(EdgeInsets(top: -12, leading: 0, bottom: 0, trailing: 0))

or by offset:

        Form {
            Section {
                Picker("Picker", selection: $selectedOption) {
                    Text("Option 1").tag(1)
                    Text("Option 2").tag(2)
                }
                .offset(x: 0, y: -8) // here
                .pickerStyle(.segmented)
                .listRowInsets(.init())
                .listRowBackground(Color.white) // demo only, should be .clear

            } header: {
                Text("Pick an option")
            }
        }

enter image description here