iosswiftuiwidthpickersegmentedcontrol

Displaying Segmented Picker at Intrinsic Size in SwiftUI


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.


Solution

  • Use fixed size as shown below

    demo

        Picker("Value", selection: $value) {
            Text("One").tag(1)
            Text("Two").tag(2)
        }
        .pickerStyle(SegmentedPickerStyle())
        .fixedSize()                           // << here !!