使用IB从View Controller的视图加载带有XIB的自定义UIView [英] Load custom UIView with XIB from a View Controller's view using IB
问题描述
我有一个使用Interface Builder构建的自定义 UIView
( MyCustomUIView
)。我想将此自定义视图放在 MyViewController
的视图中,该视图也是使用IB设计的。我在 MyViewController
的XIB中放置了一个 UIView
作为子视图,并将它的类设置为 MyCustomUIView
。问题是,当我运行代码时,只显示一个空白视图。 (当我在代码中实例化 MyCustomUIView
时,它显示得很好。)
I have a custom UIView
(MyCustomUIView
) which is built using Interface Builder. I'd like to place this custom view in MyViewController
's view, which is also designed using IB. I've placed an UIView
as a subview in MyViewController
's XIB and set it's class to MyCustomUIView
. The problem is, when I run the code, only a blank view appears. (When I instantiate MyCustomUIView
in code, it displays well.)
我只是重写 initWithFrame:
方法如下 MyCustomUIView.m
:
- (id)initWithFrame:(CGRect)frame
{
[[NSBundle mainBundle] loadNibNamed:@"MyCustomUIView" owner:self options:nil];
self = self.view;
return self;
}
我该怎么做才能正确加载视图?怎么应该 initWithCoder:
看起来像?
What should I do to make the view load properly? How should initWithCoder:
look like?
推荐答案
你是对的。 IB使用initWithCoder。 initWithCoder应该看起来与你的其他init方法非常相似:
You are correct. IB uses initWithCoder. initWithCoder should look very similar to your other init methods:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
// CUSTOM INITIALIZATION HERE
}
return self;
}
一旦你在IB中分配你的班级,你就不需要实例化它了从捆绑中除非我误解了你的意图。
Once you assign your class within IB, you won't need to instantiate it from the bundle unless I'm misunderstanding your intention.
这篇关于使用IB从View Controller的视图加载带有XIB的自定义UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!