[英]How do I associate a nib (.xib) file with a UIView?
I have a subclass "s" of UIView. 我有UIView的子类“ s”。 I want to put some buttons and labels on s.
我想在s上放置一些按钮和标签。 How do I associate my UIView subclass with a nib file?
如何将UIView子类与nib文件相关联?
You should be able the drag buttons in. To get at the nib from code, use -[NSBundle loadNibNamed:owner:options:]
. 您应该可以使用拖动按钮。要使用代码来实现笔尖,请使用
-[NSBundle loadNibNamed:owner:options:]
。 Your view should be the first object in the returned array. 您的视图应该是返回数组中的第一个对象。
In my case, I didn't want my view controller to have any knowledge of the IBOutlets from my view's .xib. 就我而言,我不希望我的视图控制器从我的视图的.xib中了解IBOutlets。 I wanted my view subclass to own the IBOutlets.
我希望我的视图子类拥有IBOutlets。 Unfortunately UIView doesn't have an
initWithNibName:
method, so I just created my own category. 不幸的是,UIView没有
initWithNibName:
方法,因此我只是创建了自己的类别。
Here's what I did: 这是我所做的:
initWithNibName:
to instantiate your view. initWithNibName:
实例化视图。 And here's the category I created: 这是我创建的类别:
- (instancetype)initWithNibName:(NSString *)nibName
{
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
if (arrayOfViews.count < 1) {
return nil;
}
self = arrayOfViews[0];
return self;
}
Inspired by this post . 受此职位启发。
Note though, that so far the frame will adjust automatically, so unlike the code in the post, I haven't yet had to explicitly set the frame. 但是请注意,到目前为止,框架会自动调整,因此与文章中的代码不同,我还没有明确设置框架。 Also, unlike the post's code, I needed to set
owner:self
so the IBOutlets would be wired up correctly. 另外,与帖子的代码不同,我需要设置
owner:self
以便IBOutlets正确连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.