iOS loadNibNamed confusion, what is best practice?

前端 未结 3 1334
野的像风
野的像风 2020-12-14 02:08

I\'m familiar with most of the process of creating an XIB for my own UIView subclass, but not everything is working properly for me - it\'s mostly to do with the IBOutlets l

3条回答
  •  北海茫月
    2020-12-14 02:45

    The second option is the correct one. The most defensive code you could do is like this:

    + (id)loadNibNamed:(NSString *)nibName ofClass:(Class)objClass {
        if (nibName && objClass) {
            NSArray *objects = [[NSBundle mainBundle] loadNibNamed:nibName 
                                                             owner:nil 
                                                           options:nil];            
            for (id currentObject in objects ){
                if ([currentObject isKindOfClass:objClass])
                    return currentObject;
            }
        }
    
        return nil;
    }
    

    And call like this:

    MyClass *myClassInstance = [Utility loadNibNamed:@"the_nib_name" 
                                             ofClass:[MyClass class]]; 
    // In my case, the code is in a Utility class, you should 
    // put it wherever it fits best
    

    I'm assuming your MyClass is a subclass of UIView? If that's the case, then you need to make sure that the UIView of your .xib is actually of MyClass class. That is defined on the third Tab on the right-part in the interface builder, after you select the view

提交回复
热议问题