笔尖会自动添加到屏幕上
我有一个 nib 文件,我正在尝试在代码中实例化。我的 UIViewController 的主视图也是从 nib 文件加载的。
这是我的 UIViewController 的 viewDidLoad 方法:
- (void)viewDidLoad
{
[super viewDidLoad];
UINib *nib = [UINib nibWithNibName:@"MyCustomView" bundle:nil];
NSArray *nibViews = [nib instantiateWithOwner:self options:nil];
MyCustomView *myView = [nibViews objectAtIndex:0];
myView.frame = CGRectMake(100.0f, 100.0f, 91.0f, 91.0f);
[self.view addSubview:myView];
}
这会创建某种无限循环。如果我注释掉 [self.view addSubview:myView],则会出现 myView,但当前屏幕上的所有内容都会消失。我不认为 instantiateWithOwner 将视图添加到屏幕上。如果存在,我如何访问它?
感谢您的帮助。
I have a nib file I'm trying to instantiate in code. My UIViewController's main view is also loaded from a nib file.
Here's my UIViewController's viewDidLoad method:
- (void)viewDidLoad
{
[super viewDidLoad];
UINib *nib = [UINib nibWithNibName:@"MyCustomView" bundle:nil];
NSArray *nibViews = [nib instantiateWithOwner:self options:nil];
MyCustomView *myView = [nibViews objectAtIndex:0];
myView.frame = CGRectMake(100.0f, 100.0f, 91.0f, 91.0f);
[self.view addSubview:myView];
}
This creates some sort of endless loop. If I comment out [self.view addSubview:myView], myView appears, but everything currently on the screen disappears. I didn't think instantiateWithOwner added the view to the screen. If it does, how do I get access to it?
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
instantiateWithOwner
方法将视图控制器的属性(从创建控制器的笔尖设置)重新分配给新笔尖的属性。这些属性可能包括view
属性,因此该方法中包含对setView:
的调用,并将视图控制器的视图设置为新笔尖的视图。之后,您尝试将视图添加为自身的子视图,这自然会导致问题。您想要创建自己的属性,例如
secondaryView
,将笔尖的视图设置为该属性,并将其添加为子视图。您不想重新分配视图控制器的视图。The
instantiateWithOwner
method reassigns the properties of your view controller (set from the nib the controller was created from) to ones from the new nib. Those properties likely include theview
property, so that method, within it, contains a call tosetView:
, and sets the view controller's view to the new nib's view. Afterwards, you're trying to add a view as a subview to itself, and that, naturally, causes problems.You want to create your own property, for instance,
secondaryView
, set the nib's view to that, and add it as a subview. You don't want to reassign your view controller's view.