2

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?

  • There are some classes, like UISwitch, that force their dimensions, Segmented Control might be one, your best bet is probably to recreate it to fit your design. – EmilioPelaez Sep 03 '19 at 13:11
  • UISegmentedControl doesn't like to be resized manually, it's height is not under your control. Best use an alternative like [MultiSelectSegmentedControl](https://github.com/yonat/MultiSelectSegmentedControl) or [BetterSegmentedControl](https://github.com/gmarm/BetterSegmentedControl). – Yonat Sep 03 '19 at 13:23

3 Answers3

3

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
}
DonMag
  • 69,424
  • 5
  • 50
  • 86
1

Same question as this: iOS: change the height of UISegmentedcontrol

By the way, you can also change the scale by changing views transform.

var segmentedControl = UISegmentedControl(frame: CGRect(x: 0, y: 0, width: w, height: h))
segmentedControl.transform = CGAffineTransform(scaleX: x, y: y)
slamballais
  • 3,161
  • 3
  • 18
  • 29
Amyth
  • 383
  • 3
  • 9
0

Just set the frame to tableView.tableHeaderView. Don't use constraints.

tableView.tableHeaderView?.frame.size.height = 50
えるまる
  • 2,409
  • 3
  • 24
  • 44