Accessing parent view when adding subview

Ethan picture Ethan · Dec 5, 2011 · Viewed 7.8k times · Source

I have a ViewController that has 2 NSViews in it of different sizes. 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). 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. 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. 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

[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.

Answer

MadhavanRP picture MadhavanRP · Dec 5, 2011

The parentViewController property should be set in the first place. 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. 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.