Search code examples
iosobjective-cviewcontrollerparentviewcontrolleruicontainerview

Accessing and manipulating parent view controllers views from a container view IOS


I am making an app where I have a container view that is half the screen of my view controller. From the container view controller's class I am trying to access and manipulate a view that sits out side of the container view. (picture below)

enter image description here

I am trying to access and add items to the scroll view from the container view class like so:

parent = (GFProfileViewController*)[self parentViewController];
UIScrollView  *scroll = (UIScrollView *)[parent.view viewWithTag:222];
parent.titleHolders.contentSize = CGSizeMake(320 * 4,60);
UILabel *testLabel = [[UILabel alloc] init];
[testLabel setFrame:CGRectMake(0, 0, 100, 40)];
[testLabel setText:@"My Test label"];
[parent.titleHolders addSubview:testLabel];
scroll.backgroundColor = [UIColor blueColor];

how ever does not work. I tried even accessing the view from the parents "view with tag" method.

neither works.

I know the code is fine because when I move it to the parent vc all works as expected. I need to be able to manipulate the view from the container though. Can anyone help?


Solution

  • As nhgrif says, don't do that.

    You should treat another view controller's views as private.

    Again, as nhgrif says, create a public method in the parent view controller that takes the information needed and does the displaying itself.

    If the view controllers are just being initialized then the parent view controller's view hierarchy may not exist yet. In that case you'd want to set properties to hold the value(s) you want to display, and then display them in your viewWillAppear method.

    With storyboards and iOS >= 6, you can set up the child view controller using an embed segue, and then in your prepareForSegue method you can set the parent view controller up as the child view controller's delegate. That's a clean way to have the child communicate back to the parent. (I have a sample app on github that demonstrates this technique if you need a more detailed explanation.)