peco peco - 4 months ago 8
iOS Question

Ensure that a view's IBOutlets have been instantiated

I have a view which subclasses

UIView
:

class MyView: UIView {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myButton: UIButton!
//..
}


The
IBOutlet
s are specified in a
nib
. I also instantiate
MyView
from the
nib
.

If
MyView
has a view controller, I would use
viewDidLoad
to determine when
myLabel
and
myButton
are instantiated. However, this is not the case here, as
MyView
is instantiated directly from a
nib
.

What should I do to determine when the two
IBOutlet
s are instantiated in this case?

Answer

The method you're looking for is awakeFromNib():

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

Implement awakeFromNib() in your MyView class, and it will be called when that view's outlets are connected.