来自xib的自定义UIView总是具有600 pt的高度(UIView-Encapsulated-Layout-Height约束)

时间:2015-04-06 03:42:58

标签: ios uitableview uiview autolayout

我正在加载自定义UIView(来自xib文件)作为UITableView的标题视图:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return NSBundle.mainBundle().loadNibNamed("ActivityFeedHeaderView", owner: nil, options: nil)[0] as ActivityFeedHeaderView
}

但是无论我的自动布局约束如何,UIView的高度始终为600.所有子视图都有高度约束和垂直空间约束,因此UIView的总高度应由此定义。但是我遇到了这些约束冲突:

(
    "<NSLayoutConstraint:0x7fae10c1d160 V:[UILabel:0x7fae10c39340'Something'(24)]>",
    "<NSLayoutConstraint:0x7fae10c4bdc0 V:[UILabel:0x7fae10c6e850'Area 31'(17)]>",
    "<NSLayoutConstraint:0x7fae10c59510 V:[UITableView:0x7fae11078400(308)]>",
    "<NSLayoutConstraint:0x7fae10c276e0 V:|-(33)-[UILabel:0x7fae10c39340'Something']   (Names: '|':Fruitful_Reports.ActivityFeedHeaderView:0x7fae10c6ed00 )>",
    "<NSLayoutConstraint:0x7fae10c27780 V:[UILabel:0x7fae10c39340'Something']-(8)-[UILabel:0x7fae10c6e850'Area 31']>",
    "<NSLayoutConstraint:0x7fae10c27870 V:[UITableView:0x7fae11078400]-(20)-|   (Names: '|':Fruitful_Reports.ActivityFeedHeaderView:0x7fae10c6ed00 )>",
    "<NSLayoutConstraint:0x7fae10c278c0 V:[UILabel:0x7fae10c6e850'Area 31']-(24)-[UITableView:0x7fae11078400]>",
    "<NSLayoutConstraint:0x7fae10f869d0 'UIView-Encapsulated-Layout-Height' V:[Fruitful_Reports.ActivityFeedHeaderView:0x7fae10c6ed00(600)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7fae10c59510 V:[UITableView:0x7fae11078400(308)]>

我不想要的限制是:

"<NSLayoutConstraint:0x7fae10f869d0 'UIView-Encapsulated-Layout-Height' V:[Fruitful_Reports.ActivityFeedHeaderView:0x7fae10c6ed00(600)]>"

为什么系统会添加它,有没有办法可以删除它?干杯

修改

添加此约束是因为600是从此方法返回的值:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    headerView = (NSBundle.mainBundle().loadNibNamed("ActivityFeedHeaderView", owner: nil, options: nil)[0] as ActivityFeedHeaderView)

    return headerView!.frame.size.height
}

但我仍然想知道,如何根据其子视图的高度和垂直空间限制让headerView更新其高度?

1 个答案:

答案 0 :(得分:0)

问题是我正在实施:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    ...
}

我删除了该方法,并将这些设置添加到UITableView,现在标题显示正确的高度:

self.tableView.estimatedSectionHeaderHeight = 300.0
self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension