1
votes

I have a UIView and I initialize it from a nib file.

In my nib file I dragged and dropped a UIImageView and I changed the class name to MyImage.

When i load the view it doesn't seem like it's initializing the the image using my custom class, because the init method is not getting called. Any idea what the problem is?

@interface MyView : UIView
@property (nonatomic, retain) IBOutlet MyImage *image;
@end

@implementation MyView
@synthesize image;

- (id)init
{
   self = [super initWithNibName:@"MyView" bundle:nibBundleOrNil];
   return self;
}
@end

Here is MyImage Here is my Image

@interface MyImage : UIImageView
@end

@implementation MyImage
- (id)init
{
   // This doesn't get called 
   self = [super init];
   if (self) 
   {
      // do somethin
   }
   return self;
}
@end
3
I'm new to iOS so please forgive me for such question. Does really UIView have initWithNibName: bundle initializer? as you've used it in your code snippet.anonim

3 Answers

4
votes

The initializer that's used when loading a view from a nib is -initWithCoder:, not -init. From the UIView reference page:

initWithCoder:—Implement this method if you load your view from an Interface Builder nib file and your view requires custom initialization.

Moreover, if you're instantiating the view programmatically, the usual initializer is -initWithFrame:.

So, change your -init method to -initWithCoder:, or implement -initWithCoder: such that it calls your -init.

1
votes

Caleb is right, implement it like so :

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self) {
        self.userInteractionEnabled = YES;
        // other stuff
    }
    return self;
}
0
votes

I though awakeFromNib was safer as all outlets wired up correctly

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self) {
        //self.userInteractionEnabled = YES;
        // other stuff
    }
    return self;
}

- (void)awakeFromNib
{
    ..setup view
}

Called in order:

initWithCoder
awakeFromNib