Instantiating a UIView from a XIB file with itself as the file's owner?

血红的双手。 提交于 2019-12-06 07:35:35

After some digging I found a workaround. Basically instead of linking my IBOutlets and IBActions to the file's owner I linked them directly to the root view's class (which has the IB-properties exposed via the custom subclass).

The key was to just not rely on the file's owner and instead connect outlets and actions directly to the custom view.

This is the initializer I ended up going with:

- (instancetype)initFromNib {
    return [[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil] firstObject];
}

This seems to be working fine now.

UPDATE

I've create a category on UIView for initializing views from XIBs (it assumes the XIB name is the same as the class name).

UIView+Initialization.h

#import <UIKit/UIKit.h>

@interface UIView (Initialization)

- (instancetype)initFromNib;

@end

UIView+Initialization.m

#import "UIView+Initialization.h"

@implementation UIView (Initialization)

- (instancetype)initFromNib {
    return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:nil options:nil] firstObject];
}

@end

You can then simply do:

MyView *myView = [[MyView alloc] initFromNib];

Assuming you have a MyView.xib file with a root view who's class is MyView.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!