0

I created a simple Picker like so:

struct ContentView: View {
    private let options = ["Action", "Comedy", "Drama", "Horror", "Zombie"]
    @State var selection = "Action"
    var body: some View {
        VStack {
            Picker("Select Genre", selection: $selection) {
                ForEach(options, id: \.self) { item in
                    HStack {
                        Text(item)
                        Image(systemName: "heart.fill")
                    }
                }
            }
        }
        .padding()
    }
}

enter image description here

When it displays I can see that it is slightly left aligned in the screen. Is there any way to fix this? Also, is there any way to detect when the Picker is showing its options?

2
  • I'm pretty sure the answer to both is no, unless you change the picker style to something like .wheel. Commented Nov 24, 2023 at 3:32
  • That's too bad :( Hopefully it is fixed in future releases. Commented Nov 24, 2023 at 4:12

1 Answer 1

0

The options menu moves with the Picker, so by adding padding to the Picker you can center it. But then, the Picker itself is a bit off-center. You could mask this by showing the same Picker as an overlay, without the padding. If you apply .allowsHitTesting(false) to the overlay then it becomes inactive, so when you tap it, the tap passes through and you get the menu from the base Picker.

This kind of workaround may break if the layout changes in a future iOS version. So I would only suggest using it for iOS versions that you have actually tested.

Like this:

private var thePicker: some View {
    Picker("Select Genre", selection: $selection) {
        ForEach(options, id: \.self) { item in
            HStack {
                Text(item)
                Image(systemName: "heart.fill")
            }
        }
    }
}

var body: some View {
    VStack {
        if #available(iOS 17.3, *) {
            thePicker
        } else if #available(iOS 17.0, *) {
            thePicker
                .padding(.leading, 16)
                .overlay {
                    thePicker
                        .background(Color(UIColor.systemBackground))
                        .allowsHitTesting(false)
                }
        } else {
            thePicker
        }
    }
    .padding()
}

Screenshot

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.