【发布时间】:2013-02-19 09:51:38
【问题描述】:
我使用 CustomView.xib 文件创建 CustomView:UIView。 现在我想通过将视图拖到另一个 XIB(例如:UIViewController.xib)并选择类:customView 来使用它。
我初始化CustomView并将SubView添加到另一个视图时可以加载成功:
- (void)viewDidLoad{
//Success load NIB
CustomView *aView = [[CustomView alloc] initWithFrame:CGRectMake(40, 250, 100, 100)];
[self.view addSubview:aView];
}
//自定义视图.m
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSLog(@"INIT");
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
[[nib objectAtIndex:0] setFrame:frame];
self = [nib objectAtIndex:0];
}
return self;
}
在这种情况下,通过将CustomCell绘制到另一个XIB中来重用它,然后将类指定为CustomView。我知道 awakeFromNib 被调用,但不知道如何加载 CustomView.xib。 该怎么做?
*编辑:
initWithCoder 在指定类时也会被调用,但它会创建一个循环并与 loadNibNamed 一起崩溃。为什么会这样?
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
NSLog(@"Coder");
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"QSKey" owner:nil options:nil];
[[nib objectAtIndex:0] setFrame:self.bounds];
self = [nib objectAtIndex:0];
}
return self;
}
【问题讨论】:
-
没有得到你..你到底想要什么??
-
我想将CustomView与其xib一起加载但不使用initWithFrame,只需将视图拖到另一个Xib然后指定类。但是XIB不加载。
-
我想这就是你想要做的,不是吗? stackoverflow.com/a/5096476/840428
-
@followben 谢谢!和我的问题一样。但是我在 initWithCoder 中做了同样的事情,它创建了一个循环,我的应用程序崩溃了!仍在调查!
-
那是因为您仍在尝试将 self 设置为在 nib 中实例化的对象,这将反过来实例化一个新实例,该实例将尝试将 self 设置为在最后一个 nib 中实例化的对象。 ..等等无限循环。在我链接到的答案中,请注意他正在拉出对象并将其设置为子视图,而不是将其设置为 self。