如何在 table 视图 header 视图中使用 UISegmentedControl 自动调整 UIView 的大小

How to autoresize UIView with UISegmentedControl in table view header view

当我创建 UISegmentedControl 并将其设置为 table 视图的 header 视图且未为其分配任何框架时,控件会自动调整大小以跨越 table 视图的宽度并保持其固有高度。

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

但是,当我将分段控件包裹在另一个 UIView 中时,视图崩溃并且未正确调整大小。

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

如何使 UIView 的行为与 UISegmentedControl 相同?在初始配置方面,我找不到两者之间的任何区别。

在这里回答我自己。我发现用 arbitrary-width 和 desired-height 框架初始化视图,然后使用自动布局使分段控件跨越视图就可以了。

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

框架的宽度似乎被忽略了,header 视图总是调整到 table 视图的宽度。但是,必须设置专用高度。

我的猜测是

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

内部调用 init(frame:) 使用启用此机制的默认框架。另一方面,

UIView()

显然用 CGRectZero 调用 init(frame:),这使得 header 崩溃。