How can I make my Nib load correctly my customized UIScrollView subclass?
-
08-07-2019 - |
Question
I had an nice UIScrollView inside my nib, which worked nicely. Then I had some very special needs and subclassed UIScrollView. In my Nib, I changed the class in the identity inspector to my subclass.
But for some reason, my -initWithFrame: method gets never called when the nib loader builds up all those objects from the nib. Actually I didn't change anything right now in my subclass. And the scroll view just works fine. Expect that it seems to be a blank UIScrollView even if I told the nib it should be an SpecializedUIScrollView for testing purposes.
Is there something else I must consider when subclassing a UIScrollView while still using a Nib file to bring it into perspective?
My dedicated initializer looks like this:
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
NSLog(@"Hello !!!!!!!!!!!!!");
}
return self;
}
I'm never seeing that Hello in the console, if I try to load that from the Nib. Of course, if I alloc and initialize that by myself, it works. But I dont want to position my scroll view programmatically around, if I can use that damn cool Interface Builder instead.
Solution
Objects in a nib or xib are stored as serialized objects, this may mean you have to use the awakeFromNib
method because init methods are never called.
OTHER TIPS
Extend initWithCoder
, be sure to call the super method. It is during this super call that setFrame
will be called on your class.
You can then re-use your standard initWithFrame
call in initWithCoder
, and the interface builder will control the frame size.
- (id)initWithCoder:(NSCoder *)aDecoder {
[super initWithCoder:aDecoder]; // Required. setFrame will be called during this method.
return [self initWithFrame:[self frame]];
}