Subclassing a UIView subclass loaded from a nib

后端 未结 2 600
北荒
北荒 2021-02-08 01:26

I have a class, FooView, that is a subclass of UIView, and whose view is loaded from a nib, something like:

+ (instancetype)viewFromNib         


        
2条回答
  •  不要未来只要你来
    2021-02-08 02:10

    I'm not sure you are onto the best solution, but I think this is what you are looking for.

    + (instancetype)viewFromNib
    {
        NSString *className = NSStringFromClass([self class]);
        NSArray *xib = [[NSBundle mainBundle] loadNibNamed:className owner:self options:nil];
        return [xib objectAtIndex:0];
    }
    

    That is as long as you can be sure that the NIB has the same name as the class.


    After realizing that I mistook one of the requirements, I say I'll have to agree with @bbum.

    - (id)init
    {
        // NOTE: If you don't know the size, you can work this out after you load the nib.
        self = [super initWithFrame:GCRectMake(0, 0, 320, 480)];
        if (self) {
            // Load the nib using the instance as the owner.
            [[NSBundle mainBundle] loadNibNamed:@"FooView" owner:self options:nil];
        }
        return self;
    }
    
    + (instancetype)viewFromNib
    {
        return [[self alloc] init];
    }
    

提交回复
热议问题