0

I have added a UIButton in a Viewcontroller on the storyboard. I subclass this button, set an outlet to the ViewController and I am able to change it's background colour with the public changeColor function.

But I want to do this in a constructor so that I don't have to do it from outside. I try figure out what constructor is called by default, but in the example below i get no outputs. Is there a constructor that is called by default only by adding an object to the storyboard?

- (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]];
}
user1506145
  • 5,176
  • 11
  • 46
  • 75

3 Answers3

3

I belive its initWithCoder. But in your case you should probably not subclass UIButton just to change color. Just do it in your viewcontrollers viewdidload, (not init outlets may not be set there).

Peter Segerblom
  • 2,773
  • 1
  • 19
  • 24
  • 1
    @user1506145: Peter is actually correct on this one. Changing the background color alone really doesn't seem to be the good enough reason for subclassing. – Rok Jarc Nov 02 '13 at 08:40
2

You need to override initWithCoder method. This constructor called when loading a view from nib or storyboard.

Avi Tsadok
  • 1,843
  • 13
  • 19
1

In your case you could try:

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

    return self;
}

A bit more universal solution can be found here.

Community
  • 1
  • 1
Rok Jarc
  • 18,765
  • 9
  • 69
  • 124