Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to center a Picker using SwiftUI

Tags:

ios

swift

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

like image 638
Quinn Avatar asked Dec 11 '19 19:12

Quinn


3 Answers

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)

like image 123
brady Avatar answered Nov 08 '22 23:11

brady


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()
like image 2
shraddha11 Avatar answered Nov 08 '22 23:11

shraddha11


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()
  }
}
like image 2
Roland Lariotte Avatar answered Nov 08 '22 23:11

Roland Lariotte