9

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.

Anton
  • 2,512
  • 2
  • 20
  • 36

1 Answers1

25

Use fixed size as shown below

demo

    Picker("Value", selection: $value) {
        Text("One").tag(1)
        Text("Two").tag(2)
    }
    .pickerStyle(SegmentedPickerStyle())
    .fixedSize()                           // << here !!
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Do you know how can I increase height of Picker? I tried .frame(height: 40) but it doesn't change the height of segmented control – Abrcd18 Jan 12 '22 at 20:34
  • This worked like magic! Abrcd18, try the .scaleEffect(CGSize(width: CGFloat, height: CGFloat)) modifier on your picker. – codingCartooningCPA Apr 09 '23 at 21:07