Custom UITableViewCell has nil outlets in init()

I have a UITableViewCell that has a UILabel registered and connected through storyboard.


In the custom class for this UITableViewCell, I've added


required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
      
        //labelName.translatesAutoresizingMaskIntoConstraints = false
        //labelName.addConstraint(widthConstraint)
    }


I can't run any code in that init that references an IBOutlet of the cell like this labelName though, because it crashes with error "Unexpectedly found nil while unwrapping an Optional value". I can access that label in awakeFromNib() but I can't affect the label's constraints in awakeFromNib and I was steered towards init() as where to affect this change.


Thanks for any help you might have...

Accepted Reply

Constraints should normally be added to the first common ancestor of the two views in question. You could try adding the constraint to self instead of labelName (assuming labelName is a subview of self).


Also, is labelName actually in the view hierarchy at that point? Or is it assigned to some size class that's not relevant, or programmatically added, or ???

Replies

> I can't affect the label's constraints in awakeFromNib


Hmm? awakeFromNib() is the proper place to adjust constraints, in my opinion. What happens when you make changes there? Can you show the code you're using?

I've connected the storyboard constraint to the class, and then in a particular bool situation in awakeFromNib, I call


thatConstraint.isActive = false


and


let widthConstraint = NSLayoutConstraint(item: labelName, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.width, multiplier: 0.9, constant: 0)
labelName.addConstraint(widthConstraint)

On trying to add the constraint I get the crash/error "The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x3685610 UILabel:0x3e11740'Label'.width == 0.9*appName.CustomCell2:0x3f23d80'CustomCell2'.width>

What are you trying to do ? It seems you try to reduce the width of the label by a factor 0.9 ? But you refer to self. I suspect that could create a recursion.


If you want to set the width, should write something like:


let widthConstraint = NSLayoutConstraint(item: labelName, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.9, constant: 100)  /
labelName.addConstraint(widthConstraint)

Constraints should normally be added to the first common ancestor of the two views in question. You could try adding the constraint to self instead of labelName (assuming labelName is a subview of self).


Also, is labelName actually in the view hierarchy at that point? Or is it assigned to some size class that's not relevant, or programmatically added, or ???

Yes! Amazing. Had to add the constraint to self instead of adding it to the label. Thank you!