UITableViewCell contentView subview breaks AutoLayout constraints

727 Views Asked by At

I am creating table view (code-only)

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

Inside a cell MyCell I have a subview

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

I am trying to set this view up (in initializer) by adding it as a subview for 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)
])

Although, this configuration results in breaking of constraints

    [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.

Interesting fact is that if I add subview as a view directly (addSubview(roundedContentView)), constraints are satisfied. I have tried adding estimated row height, as well as force re-layouting view, but nothing happens. What am I doing wrong?

0

There are 0 best solutions below