【问题标题】:How to autoresize UIView with UISegmentedControl in table view header view如何在表格视图标题视图中使用 UISegmentedControl 自动调整 UIView 的大小
【发布时间】:2015-12-15 16:35:34
【问题描述】:

当我创建一个UISegmentedControl 并将其设置为表格视图的标题视图而不为其分配任何框架时,控件会自动调整大小以跨越表格视图的宽度并保持其固有高度。

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 相同?在初始配置方面,我找不到两者之间的任何区别。

【问题讨论】:

    标签: swift uitableview uisegmentedcontrol


    【解决方案1】:

    在这里回答自己。我发现使用任意宽度和所需高度的框架初始化视图,然后使用自动布局使分段控件跨越视图就可以了。

    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
    

    似乎框架的宽度被忽略了,并且标题视图总是调整为表格视图的宽度。但是,必须设置专用高度。

    我的猜测是

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

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

    UIView()
    

    显然用CGRectZero 调用init(frame:),这会使标题崩溃。

    【讨论】:

    • 这仍然为我填满了宽度。
    猜你喜欢
    • 2013-01-22
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2014-09-02
    相关资源
    最近更新 更多