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 u开发者_开发百科sing 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
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
.
Caleb is right, implement it like so :
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if(self) {
self.userInteractionEnabled = YES;
// other stuff
}
return self;
}
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
精彩评论