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.
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
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With