简体   繁体   English

初始化后访问自定义UIButton类中的出口

[英]Access outlets in a custom UIButton class after initialization

If have a custom UIButton class and want to access its titleLabel outlet after initialization. 如果有一个自定义UIButton类,并希望在初始化后访问其titleLabel插座。 Normally one would do that in the viewDidLoad method but this only works for the Controller classes. 通常会在viewDidLoad方法中执行此操作,但这仅适用于Controller类。 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. UIButton子类中实现-awakeFromNib

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. nib加载基础结构将awakeFromNib消息发送到从nib归档重新创建的每个对象,但只有在归档中的所有对象都已加载并初始化之后。 When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established. 当一个对象收到一个awakeFromNib消息时,它保证已经建立了所有的插座和动作连接。

You must call the super implementation of awakeFromNib to give parent classes the opportunity to perform any additional initialization they require. 您必须调用awakeFromNib的超级实现,以便为父类提供执行所需的任何其他初始化的机会。 Although the default implementation of this method does nothing, many UIKit classes provide non-empty implementations. 虽然此方法的默认实现不执行任何操作,但许多UIKit类提供非空实现。 You may call the super implementation at any point during your own awakeFromNib method. 您可以在自己的awakeFromNib方法中随时调用超级实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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