How to set height of segmented controller in SwiftUI?

1.1k Views Asked by At

Is there any way to change the height of segmented controller in SwiftUI or it can be achieved with only creating custom segmented controller? I tried .frame(height) but nothing has changed. I need to increase the height of segmented controller.

@State private var userType = 0

init() {
    UISegmentedControl.appearance().selectedSegmentTintColor = .white
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.blue], for: .selected)
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.lightGray], for: .normal)
}

var body: some View {
    VStack {

    HStack {
        Picker("Choose user type", selection: $userType) {
            Text("User")
                .tag(0)
            Text("Administrator")
                .tag(1)
        }
        .pickerStyle(.segmented)
        .frame(height: 40)
        .padding(.horizontal, 16)
        }
}}

enter image description here

1

There are 1 best solutions below

1
Hoàng Huân Trần On

You can override function didMoveToSuperview:

extension UISegmentedControl {
  override open func didMoveToSuperview() {
     super.didMoveToSuperview()
     self.setContentHuggingPriority(.defaultLow, for: .vertical)  
   }
}

After set height for Picker

 Picker("", selection: $tab) {
   Text("Tab 1")
       .font(getFont(15))
       .tag(.tab1)
                      
   Text("Tab 2")
       .font(getFont(15))
       .tag(.tab2)
               
 }.frame(height: 30)