3

I have a view which subclasses UIView:

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

The IBOutlets 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 IBOutlets are instantiated in this case?

peco
  • 1,411
  • 3
  • 17
  • 38

2 Answers2

4

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.

Cocoatype
  • 2,572
  • 25
  • 42
3

If you create it from nib, like this

[[NSBundle mainBundle] loadNibNamed:@"myXib" owner:self options:nil]

outlets will be initiated right after this line.

alexey.metelkin
  • 1,309
  • 1
  • 11
  • 20