对UITableViewHeaderFooterView的约束导致UIViewAlertForUnsatisfiableConstraints

时间:2017-11-03 05:49:22

标签: ios swift autolayout

现在茫然地主演了一段时间,可能太长了,所以我在这里试试。

这是我看到的错误:

2017-11-02 22:43:23.972361-0700 TableViewCellHeaderViewLayoutTest[88247:17250641] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x60c000092930 V:|-(12)-[UILabel:0x7fd450c0eb80'Header 1']   (active, names: '|':_UITableViewHeaderFooterContentView:0x7fd450c0f290 )>",
    "<NSLayoutConstraint:0x60c0000927f0 UILabel:0x7fd450c0eb80'Header 1'.bottom == _UITableViewHeaderFooterContentView:0x7fd450c0f290.bottom - 6   (active)>",
    "<NSLayoutConstraint:0x60c000092ac0 'UIView-Encapsulated-Layout-Height' _UITableViewHeaderFooterContentView:0x7fd450c0f290.height == 17.5   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x60c0000927f0 UILabel:0x7fd450c0eb80'Header 1'.bottom == _UITableViewHeaderFooterContentView:0x7fd450c0f290.bottom - 6   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

这是我的UITableViewHeaderFooterView子类的超级简单实现:

class TableViewSectionHeaderView: UITableViewHeaderFooterView {

    let titleLabel = UILabel()

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)

        contentView.backgroundColor = .gray

        titleLabel.backgroundColor = contentView.backgroundColor
        titleLabel.font = UIFont.preferredFont(forTextStyle: .footnote)

        contentView.addSubview(titleLabel)

        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12).isActive = true
        titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 6).isActive = true
        titleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -6).isActive = true
        titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -6).isActive = true
    }

}

对我来说突出的是这种约束:

"<NSLayoutConstraint:0x60c000092ac0 'UIView-Encapsulated-Layout-Height' _UITableViewHeaderFooterContentView:0x7fd450c0f290.height == 17.5   (active)>"

如果我检查它,它也有priority 1000,这解释了为什么我自己的约束似乎失败。

一切都在视觉上很好,但我担心这个警告。我做错了什么?

1 个答案:

答案 0 :(得分:2)

看起来截面标题高度与标签的顶部和底部约束以及实际标签的固有高度竞争。部分标题可能需要根据标签的高度增大或缩小,但严格的标题高度约束会导致冲突。

将sectionHeaderHeight和estimatedSectionHeaderHeight设置为UITableViewAutomaticDimension,以允许高度调整到该部分的内容(本例中为标签)。