hennes
hennes

Reputation: 9342

How to autoresize UIView with UISegmentedControl in table view header view

When I create a UISegmentedControl and set it as a table view's header view without assigning any frame to it, the control is automatically sized to span the table view's width and keeps its intrinsic height.

let control = UISegmentedControl(items: ["one", "two"])
tableView.tableHeaderView = control

simulator screenshot with segmented control properly sized

However, when I wrap the segmented control inside another UIView, the view collapses and is not resized properly.

let header = UIView()
let control = UISegmentedControl(items: ["one", "two"])
header.addSubview(control)
tableView.tableHeaderView = header

simulator screenshot with segmented control improperly sized

How can I make the UIView behave in the same way as the UISegmentedControl? I was not able to find any difference between the two in terms of initial configuration.

Upvotes: 2

Views: 830

Answers (1)

hennes
hennes

Reputation: 9342

Answering myself here. I found out that initializing the view with an arbitrary-width and desired-height frame and then using autolayout to make the segmented control span the view does the trick.

let header = UIView(frame: CGRectMake(0, 0, 1, 33))
let control = UISegmentedControl(items: ["one", "two"])
control.translatesAutoresizingMaskIntoConstraints = false
header.addSubview(control)
header.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[control]|", options: [], metrics: nil, views: ["control": control]))
header.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[control]|", options: [], metrics: nil, views: ["control": control]))
tableView.tableHeaderView = header

It seems that the width of the frame is ignored and that the header view is always resized to the table view's width. Setting a dedicated height is, however, mandatory.

My guess is that

UISegmentedControl(items: ["one", "two"])

internally calls init(frame:) with a default frame which enables this mechanism. On the other hand,

UIView()

apparently calls init(frame:) with a CGRectZero which makes the header collapse.

Upvotes: 4

Related Questions