简体   繁体   English

添加子视图时访问父视图

[英]Accessing parent view when adding subview

I have a ViewController that has 2 NSViews in it of different sizes. 我有一个ViewController,它有两个不同大小的NSView。 I'm wanting to add the view of a custom ViewController as a subView to both of these NSViews and have it dynamically size to fill (the 2 parent views). 我想将自定义ViewController的视图作为子视图添加到这两个NSView中,并使其动态调整大小(2个父视图)。 I can accomplish this just fine in the implementation file for the main layout, but its a lot of code. 我可以在主布局的实现文件中完成这个,但它的代码很多。 I would like to instead have my custom ViewController do all the work. 我想让我的自定义ViewController完成所有工作。 To do that, I need to know the height and width of the view that I am adding my custom view to. 为此,我需要知道我添加自定义视图的视图的高度和宽度。 There is a parentViewController property, but it isn't doing anything for me. 有一个parentViewController属性,但它没有为我做任何事情。 Is there a way to reference the view that a view is being added to? 有没有办法引用视图添加到的视图?

In my custom ViewController viewDidLoad method I would like to be able to have 在我自己的自定义ViewController viewDidLoad方法中,我希望能够拥有

[self.view setFrame:CGRectMake(0, 0, 
    self.parentViewController.view.frame.size.width, 
    self.parentViewController.view.frame.size.height)];

but the height and width are both nil here. 但这里的高度和宽度都是零。

I've been digging through documentation for hours and I am still confused. 我一直在挖掘文档几个小时,我仍然感到困惑。 Any help would be much appreciated. 任何帮助将非常感激。

The parentViewController property should be set in the first place. 应该首先设置parentViewController属性。 It will be nil if it is not set. 如果没有设置它将是零。 You have not specified if it is set correctly. 您尚未指定是否正确设置。 There is a simpler way to do this though, assuming that your view's superview is set correctly. 假设您的视图的superview设置正确,有一种更简单的方法可以做到这一点。 Try this: 试试这个:

[self.view setFrame:self.superview.frame];

or make the rect from the superview's frame if you need to alter something in there. 如果你需要改变那里的东西,或者从superview的框架中制作矩形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM