从XIB加载的iOS UITableView标头

时间:2016-10-24 10:28:23

标签: ios objective-c swift uitableview autolayout

尝试从UITableView

加载XIB标头时遇到问题

在我已实施的viewDidLoad()方法中:

let tableHeaderView = NSBundle.mainBundle().loadNibNamed(
    "MyCustomHeader",
    owner: nil,
    options: nil
).first as! MyCustomHeader

tableHeaderView.translatesAutoresizingMaskIntoConstraints = false

tableView.tableHeaderView = tableHeaderView

调试器显示,tableHeaderView初始化为正确的帧。

虽然在viewDidLayoutSubviews()内,tableHeaderView身高坐到0.0

如何避免这种自动调整大小?

2 个答案:

答案 0 :(得分:0)

试试这个:

let view = (NSBundle.mainBundle().loadNibNamed("MenuHeader", owner: self, options: nil)[0] as? UIView)
tableView.tableHeaderView = view

https://stackoverflow.com/a/38450753/3901620

答案 1 :(得分:0)

可以再次应用标题高度。试试这个,

let tableHeaderView = NSBundle.mainBundle().loadNibNamed(
        "MyCustomHeader",
        owner: nil,
        options: nil
    ).first as! MyCustomHeader

    tableHeaderView.translatesAutoresizingMaskIntoConstraints = false
    tableHeaderView.setNeedsLayout()
    tableHeaderView.layoutIfNeeded()
    let height = tableHeaderView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
    var frame = tableHeaderView.frame
    tableHeaderView.size.height = height
    tableHeaderView.frame = frame
    tableView.tableHeaderView = tableHeaderView