笔尖会自动添加到屏幕上

发布于 2024-11-08 11:04:33 字数 631 浏览 0 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

生生不灭 2024-11-15 11:04:33

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 the view property, so that method, within it, contains a call to setView:, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文