Quinn
Quinn

Reputation: 9404

Unable to center a Picker using SwiftUI

I'm trying to make a picker in SwiftUI and functionally its working great. But for whatever reason it squeezes the title onto the left side of the picker, but I just want to picker to be centred in the view.

Here is my code:

import SwiftUI

struct FancyPicker: View {
    let name: String
    let options: [String]
    let doneText = "Done"
    let onSelection: (String)->Void

    @State private var selection = 0

    var body: some View {
        VStack {
            HStack {
                Text(name)
                Spacer()
                Button(action: {
                    self.onSelection(self.options[self.selection])
                }, label: {
                    Text(doneText)
                })
            }.padding()

            Picker(selection: $selection, label: EmptyView()) {
                ForEach(0 ..< options.count) { index in
                    Text(self.options[index]).tag(index)
                }
            }
        }
    }
}

struct FancyPicker_Previews: PreviewProvider {
    static var previews: some View {
        FancyPicker(name: "Test Picker", options: ["One", "Two", "Three"]) { selection in
            print("Selected \(selection)")
        }
    }
}

You can notice I have the pickers label set to an EmptyView and here is what the output looks like:

Ugly Picker View

Is there anyway to get rid of the ugly padding on the left side? There is also extra ugly padding above and below the picker but I can worry about that another day...

Upvotes: 8

Views: 3011

Answers (3)

Roland Lariotte
Roland Lariotte

Reputation: 3488

You have to hide the labels in order to center the picker. You can also edit a height and clip it to have a custom picker height.

var body: some View {
  VStack {

    Picker(selection: $selection, label: Text("") {
      ForEach(0 ..< options.count) {
        Text(self.options[$0]).tag($0)
      }
    }
    .labelsHidden()
    .frame(height: 50)
    .clipped()
  }
}

Upvotes: 5

shraddha11
shraddha11

Reputation: 773

You have to hide label of PickerView.

 Picker(selection: $selection, label: EmptyView()) {
            ForEach(0 ..< options.count) { index in
                Text(self.options[index]).tag(index)
            }
        }.labelsHidden()

Upvotes: 2

brady
brady

Reputation: 132

Use .labelsHidden() to hide the Picker's label.

Even if the label is hidden, I'd recommend adding a descriptive label so the label can be used by screen readers.

(credit)

Upvotes: 11

Related Questions