Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom view - Crash in "required init?(coder aDecoder: NSCoder)" method

Tags:

ios

swift

init

Code:

class HeaderView: UIView {

@IBOutlet weak var titleLabel: UILabel!

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    finishInit()
}

func finishInit() {
    titleLabel.backgroundColor = UIColor.white
}

func setView(withTitle title: String?) {
    titleLabel.backgroundColor  = UIColor.white
    titleLabel.text = title

}

Crash:

On finishInit() method, while setting label background color

fatal error: unexpectedly found nil while unwrapping an Optional value

But same, on setView() method, is not crashing.

like image 810
Dili Avatar asked Feb 12 '26 08:02

Dili


1 Answers

When the init methods run and return, the connections of the outlets are not yet made. Therefore the outlets are still nil and you are crashing when using it.

You should be able to test this by adding a question mark (?) after the titleLabel and thus treating it like an optional again.

titleLabel?.backgroundColor = UIColor.white

Then you will not crash but the line will also not do anything of course if the label is still nil.

So you need to call the code that uses the outlets later (which you seem to be doing with setView?

You might use awakeFromNib where the outlets should be set.

like image 154
Thomas Krajacic Avatar answered Feb 15 '26 11:02

Thomas Krajacic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!