Displaying Segmented Picker at Intrinsic Size in SwiftUI
Asked Answered
H

1

12

In SwiftUI, a Picker of style SegmentedPickerStyle occupies the full width of its enclosing view. How can I instead have it occupy only the width it requires?

Consider this: Segmented Picker which is generated by the following code:

struct ContentView: View {
    @State var value = 1
    var body: some View {
        Picker("Value", selection: $value) {
            Text("One").tag(1)
            Text("Two").tag(2)
        }
        .pickerStyle(SegmentedPickerStyle())
        .padding()
    }
}

How can I remove the large margins from the two picker choices, making the picker only as wide as it needs to be? This seems like a very basic question, but the answer eludes me.

Herzl answered 5/12, 2020 at 0:36 Comment(0)
J
33

Use fixed size as shown below

demo

    Picker("Value", selection: $value) {
        Text("One").tag(1)
        Text("Two").tag(2)
    }
    .pickerStyle(SegmentedPickerStyle())
    .fixedSize()                           // << here !!
Janitor answered 5/12, 2020 at 5:10 Comment(2)
Do you know how can I increase height of Picker? I tried .frame(height: 40) but it doesn't change the height of segmented controlCatima
This worked like magic! Abrcd18, try the .scaleEffect(CGSize(width: CGFloat, height: CGFloat)) modifier on your picker.Institutionalism

© 2022 - 2024 — McMap. All rights reserved.