Nil while unwrapping an Optional IBOutlet value

主宰稳场 提交于 2020-01-04 06:08:39

问题


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?


回答1:


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




回答2:


You can prevent the crash from happening by safely unwrapping label with an if let statement.

if let mylabel = label {
   mylabel.preferredMaxLayoutWidth = mylabel.frame.size.width
}



回答3:


You should use:

label?.preferredMaxLayoutWidth = label.frame.size.width

This before in an early call of layoutSubviews the outlet could not be yet setted, but in the next call will be. Using otional chaining you can avoid explicit optional unwrapping. if label is nil the assignment is skipped automatically.



来源:https://stackoverflow.com/questions/40397279/nil-while-unwrapping-an-optional-iboutlet-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!