iosobjective-cuiviewcontrolleruicontainerviewparentviewcontroller

Accessing parent view controller


I have a mainViewController with a container view in it. I'm trying to access theMainViewController from the container view.

Here is my code:

self.theMainViewController = (theMainViewController *)self.parentViewController;

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
[self.theMainViewController .tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];

This doesn't work. self.theMainViewController gives a nil value when I make an nslog of it. I then replaced:

self.parentViewController

to:

self presentingViewController

and it gave me the same results. How can I access the mainViewController from the container view's class?

Update

This is my setup: Static table view inside UIViewController [Xcode 5] (I can't add images, so the image posted in that answer, is the same as my setup.)


Solution

  • You can use "prepareForSegue" in the parent view controller to pass self to the container view like so:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
         if ([[segue identifier] isEqualToString:@"containerview_myIdentifier"]) {
    
             ContainerViewController *vc = [segue destinationViewController];
             [vc setReferenceToParentVC:self];
        }
    }
    

    Where you create a synthesized property in ContainerViewController of type ParentViewController and set that property to self.

    Here is what you should see in storyboard: enter image description here