john doe
john doe

Reputation: 9660

Subclassing a UIView. init method is never called

I have a UIView on the interface builder. In my view controller I have an IBOutlet MyUIView which points to the UIView on the interface builder.

I changed the class of the UIView to "MyUIView" (custom UIView class) but it seems like none of the init methods of the subclass are fired.

What am I doing wrong?

Upvotes: 17

Views: 6976

Answers (2)

Aaron Brager
Aaron Brager

Reputation: 66224

Short answer: you need to use initWithCoder:.

From the initWithFrame: docs:

If you use Interface Builder to design your interface, this method is not called when your view objects are subsequently loaded from the nib file. Objects in a nib file are reconstituted and then initialized using their initWithCoder: method, which modifies the attributes of the view to match the attributes stored in the nib file.

If you're using a nib / xib / Storyboard file, use initWithCoder:. If you're creating your view programmatically, you can use init or initWithFrame:.

Upvotes: 21

Anoop Vaidya
Anoop Vaidya

Reputation: 46533

Instead of init you need to call initWithCoder first then call init as :

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self baseClassInit];
    }
    return self;
}

- (void)baseClassInit {

    //initialize all ivars and properties    
}

Upvotes: 26

Related Questions