Loading custom UIView from nib, all subviews contained in nib are nil?

梦想的初衷 提交于 2019-11-28 03:41:24
Robin Summerhill

You may be misunderstanding how nib loading works. If you define a custom UIView and create a nib file to lay out its subviews you can't just add a UIView to another nib file, change the class name in IB to your custom class and expect the nib loading system to figure it out. You need to modify initWithCoder of your custom UIView class to programmatically load the nib that defines its subview layout. e.g.:

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
        [self addSubview:self.toplevelSubView];
    }
    return self;
}

Your custom view's nib file needs to have the 'File's owner' class set to your custom view class and you need to have an outlet in your custom class called 'toplevelSubView' connected to a view in your custom view nib file that is acting as a container for all the subviews. Add additional outlets to your view class and connect up the subviews to 'File's owner' (your custom UIView).

Alternatively, just create your custom view programmatically and bypass IB.

Check that you are calling the 'super' implementation of initWithCoder: and awakeFromNib in each of your overridden methods i.e.

- (id)initWithCoder:(NSCoder *)decoder {
    if ((self = [super initWithCoder:decoder])) {
      ...your init code...
    }
    return self;
}

- (void)awakeFromNib {
     [super awakeFromNib];
     ...your init code...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!