Search code examples
iosswiftautolayoutuikitconstraints

AutoLayout in UITableViewCell contentView


I'm trying to programmatically create constraints to center this pink UIView in a UITableViewCell. However, when I add the constraints, they don't apply and I get a message in the console that says that some NSAutoresizingMaskLayoutConstraints can't be simultaneously satisfied.

So when I set cell.contentView.translatesAutoresizingMaskIntoConstraints = false, I get this message in the console :

"Changing the translatesAutoresizingMaskIntoConstraints property of the contentView of a UITableViewCell is not supported and will result in undefined behavior, as this property is managed by the owning UITableViewCell".

The view does get centered, but the console says I shouldn't change this property.

How can I achieve this?

Before setting the property to false

After setting the property to false

Thank you very much.


Solution

  • UITableViewCell and UICollectionViewCell manages its contentView manually. In other words, UIKit relies on the cells' contentView having translatesAutoresizingMaskIntoConstraints being True so Changing the translatesAutoresizingMaskIntoConstraints property of the contentView of a UITableViewCell is not supported and will result in undefined behavior.

    Don't do this:

    cell.contentView.translatesAutoresizingMaskIntoConstraints = false
    

    So, here is the full function for adding UIView in a UITableViewCell should be look like:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    
        //if already added the subview?
        if cell.contentView.subviews.count == 0 {
    
            let view = UIView() //your pinkView
    
            view.translatesAutoresizingMaskIntoConstraints = false
            view.backgroundColor = UIColor.purple
    
            cell.contentView.addSubview(view)
    
            view.centerXAnchor.constraint(equalTo: cell.contentView.centerXAnchor).isActive = true
            view.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor).isActive = true
            view.widthAnchor.constraint(equalToConstant: 50.0).isActive = true
            view.heightAnchor.constraint(equalToConstant: 50.0).isActive = true
        }
    
        return cell
    }