好的,StackOverflow上有很多关于此的帖子,但没有一个在解决方案上特别清楚.我想UIView用随附的xib文件创建一个自定义.要求是:
UIViewController- 一个完全独立的类我目前的做法是:
覆盖 -(id)initWithFrame:
-(id)initWithFrame:(CGRect)frame {
self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
owner:self
options:nil] objectAtIndex:0];
self.frame = frame;
return self;
}
Run Code Online (Sandbox Code Playgroud)-(id)initWithFrame:在我的视图控制器中以编程方式实例化
MyCustomView *myCustomView = [[MyCustomView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
[self.view insertSubview:myCustomView atIndex:0];
Run Code Online (Sandbox Code Playgroud)这工作正常(虽然从来没有调用[super init],只是使用加载的笔尖的内容设置对象似乎有点怀疑 - 这里有建议添加一个子视图在这种情况下也工作正常).但是,我希望能够从故事板中实例化视图.所以我可以:
UIView在故事板中放置父视图MyCustomView覆盖-(id)initWithCoder:- 我见过的代码最常适合以下模式:
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self initializeSubviews];
}
return self;
}
-(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame]; …Run Code Online (Sandbox Code Playgroud)