UITableViewCell contentView子视图打破了AutoLayout约束

时间:2018-11-06 20:12:03

标签: ios swift uitableview autolayout uitableviewautomaticdimension

我正在创建表格视图(仅代码)

private lazy var tableView: UITableView = {
    let tableView = UITableView()
    tableView.dataSource = self
    tableView.translatesAutoresizingMaskIntoConstraints = false
    tableView.register(MyCell.self, forCellReuseIdentifier: "MyCellIdentifier")
    return tableView
}()

在一个单元格MyCell中,我有一个子视图

private lazy var roundedContentView: UIView = {
    let view = UIView()
    view.backgroundColor = .red
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

我试图通过将其添加为contentView的子视图来设置此视图(在初始化中)

contentView.addSubview(roundedContentView)

NSLayoutConstraint.activate([
    roundedContentView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
    roundedContentView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
    roundedContentView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8),
    roundedContentView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),
    roundedContentView.heightAnchor.constraint(equalToConstant: 200)
])

尽管如此,这种配置导致约束的破坏

    [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:0x6000031284b0 V:|-(8)-[UIView:0x7fddedd41200]   (active, names: '|':UITableViewCellContentView:0x7fddedd03410 )>",
    "<NSLayoutConstraint:0x600003136670 UIView:0x7fddedd41200.bottom == UITableViewCellContentView:0x7fddedd03410.bottom - 8   (active)>",
    "<NSLayoutConstraint:0x600003137f70 UIView:0x7fddedd41200.height == 200   (active)>",
    "<NSLayoutConstraint:0x600003137660 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fddedd03410.height == 216   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x600003137f70 UIView:0x7fddedd41200.height == 200   (active)>

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

有趣的事实是,如果我直接将子视图添加为视图(addSubview(roundedContentView)),则可以满足约束条件。我尝试添加估计的行高以及强制重新布局视图,但是没有任何反应。我在做什么错了?

0 个答案:

没有答案