在子类iOS中默认调用什么构造函数

时间:2013-11-02 08:27:37

标签: ios iphone objective-c storyboard

我在故事板上的ViewController中添加了一个UIButton。我将此按钮子类化,为ViewController设置了一个插座,我可以使用public changeColor函数更改它的背景颜色。

但我想在构造函数中执行此操作,以便我不必从外部执行此操作。我试着找出默认调用的构造函数,但在下面的例子中我没有输出。是否只有通过向故事板添加对象来默认调用构造函数?

- (id)initWithFrame:(CGRect)frame
{
    NSLog(@"constructor");

    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(id)init {
    NSLog(@"constructor");
    self = [super init];
    if (self) {
        // Initialization code
    }
    return self;
}

-(void)changeColor{
    [self setBackgroundColor:[UIColor redColor]];
}

3 个答案:

答案 0 :(得分:3)

我相信它的initWithCoder。但在你的情况下,你可能不应该只是改变颜色UIButton的子类。只需在viewcontrollers viewdidload中执行此操作(不能在那里设置init outlet)。

答案 1 :(得分:2)

您需要覆盖initWithCoder方法。从nib或storyboard加载视图时调用此构造函数。

答案 2 :(得分:1)

在您的情况下,您可以尝试:

- (id)initWithCoder:(NSCoder*)aDecoder 
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
         // Initialization code
         // calling [self changecolor]; for example
    }

    return self;
}

可以找到更加通用的解决方案here

相关问题