Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 773
john doe Avatar asked Feb 28 '13 16:02

john doe


People also ask

How do I create a custom view in Swift?

Creating Custom Views programatically. Open Xcode ▸ File ▸ New ▸ File ▸ Cocoa Touch class ▸ Add your class name ▸ Select UIView or subclass of UIView under Subclass of ▸ Select language ▸ Next ▸ Select target ▸ Create the source file under your project directory.


2 Answers

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    
}
like image 51
Anoop Vaidya Avatar answered Oct 06 '22 06:10

Anoop Vaidya


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:.

like image 34
Aaron Brager Avatar answered Oct 06 '22 05:10

Aaron Brager