I have created a UISegmentedControl
subclass that I would like to use as the section header view for a UITableView
.
I would like the custom UISegmentedControl
subclass to have a height of 50pt.
I am aware that I can create a height constraint for this. However, after setting the height constraint, if this segmented control is used as the section header of the table view, then auto layout errors are shown ( see question ).
I tried setting height by calling the init(frame:) method with appropriate height, but this has no effect.
Is there a way to set the height of the UISegmentedControl
subclass without using auto layout?
You can simply use frames
to set the size
and position
of UISegmentedControl
inside a sectionHeaderView
, i.e.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
let segmentedControl = UISegmentedControl(frame: CGRect(x: 10, y: 10, width: 200, height: 50))
segmentedControl.insertSegment(withTitle: "First", at: 0, animated: false)
segmentedControl.insertSegment(withTitle: "Second", at: 1, animated: false)
segmentedControl.selectedSegmentIndex = 0
view.addSubview(segmentedControl)
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 70
}
Screenshot: