Daumantas Versockas Daumantas Versockas - 1 month ago 12
Objective-C Question

Nil while unwrapping an Optional IBOutlet value

I have got a

fatal error: unexpectedly found nil while unwrapping an Optional value
for an
IBOutlet
.

In my custom view, I have associated my outlet with a
XIB
file. I have double checked this. This is how it looks like:

@IBOutlet weak var label: UILabel! {
didSet {
label.textColor = .redColor()
}
}


My implementation of
layoutSubviews
looks like:

override func layoutSubviews() {
super.layoutSubviews()

label.preferredMaxLayoutWidth = label.frame.size.width
}


Despite the fact, that
layoutSubviews
method has to be called after UI elements initialisation, I get an error:

fatal error: unexpectedly found nil while unwrapping an Optional value


This error is triggered by line:

label.preferredMaxLayoutWidth = label.frame.size.width


Why is that so? How to fix it?

Answer

Try doing it in viewDidLayoutSubviews instead of layoutSubviews. You UI elements should be ready in viewDidLayoutSubviews, but not necessary in layoutSubviews.