How to inherit a custom view which has a .xib file

2019-06-04 18:15发布

There is a custom view, that consist of class and xib file. I use it as

[[NSBundle mainBundle] loadNibNamed:@"myViewNib" owner:self options:nil];

Question is how to inherit this custom view.

I inherit the myViewClass, but then I can't use the code above to create a instance.I think I'm in the wrong way.

标签: ios class xib
2条回答
女痞
2楼-- · 2019-06-04 18:35

It should be:

myViewClass *newView = [[NSBundle mainBundle] loadNibNamed:@"myViewNib" owner:self options:nil];
查看更多
Deceive 欺骗
3楼-- · 2019-06-04 18:54

One option is not to create MYBaseView itself in the .xib file, but it's subview. This way you will be able to inherit MYBaseView easily.

This is the code should work correctly if you create your view object programmatically or in the Interface Builder:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setUp];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)setUp
{
    UIView *view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] lastObject];
    [self addSubview:view];
}
查看更多
登录 后发表回答