简体   繁体   中英

How do I create a general nib file? I'm confused why I have to tie it to a view controller class?

Why can I not create a nib with a UIView ? It seems I need to create it with a UIViewController . I just want to create a view with Interface Builder that I can use across multiple different view controllers.

Actually, you can - the only thing that is missing is a convenience constructor. Personally, I use snippet like this:

+ (instancetype)instanceFromNib
{
    Class ownClass = self;
    id ret = nil;

    NSArray* objects = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(ownClass) owner:nil options:nil];

    for (id obj in objects) {
        if ([obj isKindOfClass:ownClass])
            ret = obj;
    }

    return ret;
}

Only restriction is that class nib needs to be named after view class and contain object of that class (preferably only one).

If you want to have a view nib that is loaded automatically from other nibs, then it would be tricky, but also possible (with effort depending on what you want to do). In simplest version just override initWithCoder with code similar to one I pasted (tricky part begins if you need to keep properties that were in that other nib).

Also this question was probably answered on SO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM