Reputation: 612
I am trying to add a UIImageView
to a cell and programmatically add auto layout constraints. However, it is giving me this following error: The view hierarchy is not prepared for the constraint... When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled.
I looked at these following posts: Swift, Constraint, The view hierarchy is not prepared for the constraint, Why is my layout constraint returning an error in this case? (Swift), and Swift, Constraint, The view hierarchy is not prepared for the constraint. One thing that I could not add to my code that these posts were suggesting me to add is setTranslatesAutoresizingMaskIntoConstraints
. When I try to add this function to my imageView
, I get an error.
Here is my code:
func cellTwo(indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellTwo", forIndexPath: indexPath) as! CathyTaskLogTwoTableViewCell
let imageView:UIImageView = UIImageView(image: UIImage(named: "defaultPicture"))
imageView.frame.size.width = 100
imageView.frame.size.height = 31
let horizonalContraints = NSLayoutConstraint(item: imageView, attribute:
.LeadingMargin, relatedBy: .Equal, toItem: cell,
attribute: .LeadingMargin, multiplier: 1.0,
constant: 20)
imageView.addConstraint(horizonalContraints)
cell.addSubview(imageView)
return cell
}
Thank you so much in advance for your help :)
Upvotes: 1
Views: 3395
Reputation: 437432
The sequence is:
translatesAutoresizingMaskIntoConstraints
to false
;addSubview
to add it to the view hierarchy; andDo not set the frame
at all if you're using constraints. Everything should be defined by constraints.
It is probably not prudent to call dequeueReusableCellWithIdentifier
and then add a subview. What if the cell is being reused? You'll be adding the same subview multiple times. The programmatic adding of subview is probably best put in the cell subclass implementation of awakeFromNib
, if from storyboard or NIB, or init(style;, reuseIdentifier)
if building it programmatically. Or, easiest, don't programmatically create cells at all and use storyboard or NIB.
Upvotes: 1
Reputation: 1827
Before adding constraints to any view programmatically you should add it as subview and turn translatesAutoresizingMaskIntoConstraints to false and then add your required constraints. Like
cell.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
//now add your required constraints
Upvotes: 0