简体   繁体   中英

Access outlets in a custom UIButton class after initialization

If have a custom UIButton class and want to access its titleLabel outlet after initialization. Normally one would do that in the viewDidLoad method but this only works for the Controller classes. How would you access any outlet of the base class directly after initialization?

Here a little code snippet because most of the times it is more clear afterwards

- (id) initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Here the outlet is still 'nil'
    }
    return self;
}

- (void) viewDidLoad {
    // Not usable with UIControls
}

Implement -awakeFromNib in your UIButton subclass.

From the official documentation :

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.

You must call the super implementation of awakeFromNib to give parent classes the opportunity to perform any additional initialization they require. Although the default implementation of this method does nothing, many UIKit classes provide non-empty implementations. You may call the super implementation at any point during your own awakeFromNib method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM