8

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...

3 Answers 3

11

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)

4

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()
  }
}
1
  • Ended up using it without the height and without the clipped since i thought the end result was cleaner - but looks much better now, thanks!
    – Quinn
    Dec 11, 2019 at 21:49
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.