Subclassing a UIView subclass loaded from a nib

后端 未结 2 569
北荒
北荒 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:03

    Swizzling is not (ever) the answer.

    The problem is in your NIB; it is archived with object[0] being an instance of FooView, not FooSubclassView. If you want to load the same NIB with a different view subclass as object[0], you need to move the instance out of the NIB's archive.

    Probably the easiest thing to do, since your class is already loading the NIB, is make an instance of FooView or FooSubclassView the File's Owner.

    This question has a decent explanation of the File's Owner pattern. Note that you are pretty much already there in that your class is what is loading the XIB/NIB anyway.

    And here is the official docs on File's Owner.

    0 讨论(0)
  • 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];
    }
    
    0 讨论(0)
提交回复
热议问题