How to change SwiftUI Picker view size with no additional space?

Viewed 2030

I'm new to SwiftUI and trying to implement Piker view from SwftUI.

I have simple Picker with a few elements in it to display. I set a frame with to 50 only, added border to it and applied view modifier .clipped(). Heres code:

import SwiftUI

struct ContentView: View {
var body: some View {
        VStack {
            Picker(selection: .constant(1), label: Text("")) {
                Text("1").tag(1)
                Text("2").tag(2)
                Text("3").tag(3)
            }
            //.clipped()
            .labelsHidden()
            .frame(width: 50)
            .clipped()
        }
        .border(Color.red)
   }
}

Everything looks ok. But, the problem start to occur when run the app and at the moment of running just open Debug View Hierarchy and you'll see like the actual size if Picker width is much bigger and I don't know why is that happening. Please, if you know how to fix it, I'll appearance it a lot, thank you

enter image description here

1 Answers

Try with content shape, it should restrict picker hit testing only to clipped area, like

VStack { 
    Picker(selection: .constant(1), label: Text("")) { 
          Text("1").tag(1) 
          Text("2").tag(2) 
          Text("3").tag(3) 
     } //.clipped() 
     .labelsHidden()
     .frame(width: 50) 
     .clipped()
     .contentShape(Rectangle())   // << here !!
  }
Related