Search code examples
iosswiftuitableviewuisegmentedcontrol

How to change the height of the UISegmentedControl?


I am using an UISegmentedControl in an UITableView as follows-

let segmentedControl = UISegmentedControl(items: ["Segment1", "Segment2"])
tableView.tableHeaderView = segmentedControl

The above code works as expected. I would like to change the height of the UISegmentedControl. I tried to set a height constraint on the UISegmentedControl as follows-

let segmentedControl = UISegmentedControl(items: ["Segment1", "Segment2"])
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.heightAnchor.constraint(equalToConstant: 50).isActive = true
tableView.tableHeaderView = segmentedControl

When the above code is run, the height of the UISegmentedControl is set to the expected custom height. However, the leading and trailing edges of the UISegmentedControl do not snap to the leading and trailing edges of the UITableView.

I also tried to create a custom UISegmentedControl to specify the height of the UISegmentedControl without setting a height constraint as follows-

class CustomSegmentedControl: UISegmentedControl {
    override var intrinsicContentSize: CGSize {
        return CGSize(width: super.intrinsicContentSize.width, height: 50)
    }
}

The above code does not work as expected. Can anyone point out how to set the height of the UISegmentedControl so that it appears as expcted when used in UITableView?


Solution

  • By setting segmentedControl.translatesAutoresizingMaskIntoConstraints = false you're losing the default constraints.

    If you are happy with the appearance and layout of the segmented control, you just want to change its height, try this approach:

    // probably in
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let segmentedControl = UISegmentedControl(items: ["Segment1", "Segment2"])
        segmentedControl.frame.size.height = 50.0
        tableView.tableHeaderView = segmentedControl
    }