Yehya Ch.
Yehya Ch.

Reputation: 215

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.

Upvotes: 17

Views: 17450

Answers (3)

Ghulam Rasool
Ghulam Rasool

Reputation: 4064

Also, make sure that in xib of your cell, Layout should be selected to

"Autoresizing Mask"

and not "Inferred (Autoresizing Mask)"

as shown in the image

enter image description here

Upvotes: 20

Govind Kumawat
Govind Kumawat

Reputation: 1592

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
}

Upvotes: 19

Mahendra
Mahendra

Reputation: 8904

You don't need to set translatesAutoresizingMaskIntoConstraints = false to contentView of tableview cell.

You only need to set translatesAutoresizingMaskIntoConstraints = false to the view which is added dynamically and for IBOutlets translatesAutoresizingMaskIntoConstraints = false by default.

Upvotes: 2

Related Questions