52

This is tricky to word but I have a view controller (vc1) that contains a container view (I'm using storyboards). Within that container view is a navigation controller and a root view controller (vc2).

From within the vc2 how can I get access to vc1?

Or, how do I pass vc1 to vc2? (baring in mind that I'm using storyboards).

Mark Bridges
  • 8,228
  • 4
  • 50
  • 65

7 Answers7

51

You can use the prepareForSeguemethod in Vc1 as an embed segue occurs when the ContainerViewController is made a child. you can pass self as an obj or store a reference to the child for later use.

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSString * segueName = segue.identifier;
    if ([segueName isEqualToString: @"embedseg"]) {
        UINavigationController * navViewController = (UINavigationController *) [segue destinationViewController];
        Vc2 *detail=[navViewController viewControllers][0];
        Vc2.parentController=self;
    }
}

Edit: minor code fix

Chris J
  • 1,527
  • 14
  • 19
Bonnie
  • 4,943
  • 30
  • 34
  • @Firula the line `UINavigationController * navViewController = (UINavigationController *) [segue destinationViewController];` does not initialize anything its only a pointer to the already initialized Controller. – Bonnie Jan 23 '14 at 10:06
  • 1
    So first off, name the segue(link) in the storyboard that connects the container view to its first view controller. I named mine "toContainer". Then in the view controller containing the container view add this method - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString: @"toContainer"]) { UINavigationController *navViewController = (UINavigationController *) [segue destinationViewController]; UIViewController *vc2 = [navViewController viewControllers][0]; } } vc2 was the controller I wanted to get reference to. – Mark Bridges Apr 15 '14 at 10:36
  • note: destinationViewController was already my containers embedded target UIViewController – BananaAcid Sep 03 '15 at 12:15
  • This is very helpful to me, thank you. One related question: Why would my child view controller's ViewDidLoad method get called before the parent one? Have I messed something up with the set up of the container? – Chucky Jun 08 '16 at 11:12
  • @Chucky to understand this, imagine the Child is essentially a part(uicontrol) of the Parent and parents `-(void)viewDidLoad` is incomplete unless all the UIElements are loaded. Therefore the Child's `-(void)viewDidLoad` it is supposedly called before the parents. – Bonnie Jun 15 '16 at 07:38
  • but what if i have two other segues from the view controller vc2. how do i access vc1 from them? – Jenita _Alice4Real Nov 03 '16 at 10:39
  • its not good practice for a child to call method on its parent using that reference you passed in. You should instead pass the data into the child that it needs and use the delegate pattern for callbacks. – malhal Feb 09 '19 at 19:20
18

To access parent view controller from within your child view controller you must override didMoveToParentViewController:

- (void)didMoveToParentViewController:(UIViewController *)parent {
    [super didMoveToParentViewController:parent];

    //Use parent
}

On Xcode Command+Click over this method for more info:

These two methods are public for container subclasses to call when transitioning between child controllers. If they are overridden, the overrides should ensure to call the super. The parent argument in both of these methods is nil when a child is being removed from its parent; otherwise it is equal to the new parent view controller.

addChildViewController: will call [child willMoveToParentViewController:self] before adding the child. However, it will not call didMoveToParentViewController:. It is expected that a container view controller subclass will make this call after a transition to the new child has completed or, in the case of no transition, immediately after the call to addChildViewController:. Similarly removeFromParentViewController: does not call [self willMoveToParentViewController:nil] before removing the child. This is also the responsibilty of the container subclass. Container subclasses will typically define a method that transitions to a new child by first calling addChildViewController:, then executing a transition which will add the new child's view into the view hierarchy of its parent, and finally will call didMoveToParentViewController:. Similarly, subclasses will typically define a method that removes a child in the reverse manner by first calling [child willMoveToParentViewController:nil].

Firula
  • 1,251
  • 10
  • 29
10

You can use delegation using the same method Bonnie used. Here is how you do it:

In your containerViews ViewController:

class ContainerViewViewController: UIViewController {
   //viewDidLoad and other methods

   var delegate: ContainerViewControllerProtocol?

   @IBAction func someButtonTouched(sender: AnyObject) { 
    self.delegate?.someDelegateMethod() //call this anywhere
   }

}

protocol ContainerViewControllerProtocol {
    func someDelegateMethod()
}

In your parent ViewController:

class ParentViewController: UIViewController, ContainerViewControllerProtocol {
   //viewDidLoad and other methods

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "filterEmbedSegue" {
            let containerViewViewController = segue.destinationViewController as ContainerViewViewController

            containerViewViewController.delegate = self
        }
    }

    func someDelegateMethod() {
        //do your thing
    }
}
osrl
  • 8,168
  • 8
  • 36
  • 57
10

Use property parentViewController as self.parentViewController

itsji10dra
  • 4,603
  • 3
  • 39
  • 59
Borzh
  • 5,069
  • 2
  • 48
  • 64
  • 8
    In my case this didn't work as self.parentViewController was nil. I added the containerView in a storyboard, then set the associated view controller class to be my particular subclass. I expected parentViewController to be set to the VC that contained the container view, but this isn't getting set automagically. I had to use the -prepareForSegue solution above – Craig Watkinson Oct 24 '15 at 14:59
  • property is "self.parent" in swift 3 – Travis M. Sep 13 '17 at 21:51
2

Thank you Bonnie for telling me what to do. Indeed the prepare for segue method is the way to go.

I'm just clarifying the code and steps here.

So first off, name the segue(link) in the storyboard that connects the container view to its first view controller. I named mine "toContainer".

Then in the view controller containing the container view add this method

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString: @"toContainer"]) {
        UINavigationController *navViewController = (UINavigationController *) [segue destinationViewController];
        UIViewController *vc2 = [navViewController viewControllers][0];
    }
}

So vc2 was the controller I wanted to get reference to.

This worked for me, your method would be slightly different inside the prepareForSegue if your first viewconroller wasn't a navigation controller.

Mark Bridges
  • 8,228
  • 4
  • 50
  • 65
  • 3
    you could have marked my answer as correct, and added yours in comments for better clarification. – Bonnie Jan 28 '14 at 04:58
  • Mark, you need to mark Firula's or Bonnie's answer as correct, and go ahead and edit your question and put this useful information in the question. – Fattie Apr 13 '14 at 08:01
1

1) on VC2 expose a property for passing in a reference to VC1

//VC2.h
#import "VC1.h"

@interface VC2 : NSObject
@property (strong, nonatomic) VC1 *parent;
@end

2) on VC1, pass self into the property exposed in VC2 in your prepareForSegue method after you setup your segue's identifier to "ToVC2". Then pass the reference like so:

//VC1.m
@implementation VC1 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:@"ToVC2"]) {
    VC2 *vc2 = segue.destinationViewController;
    vc2.parent = self;
}
}
SmileBot
  • 19,393
  • 7
  • 65
  • 62
0

Swift - An alternative is to create a reference in parent UIViewController (vc1) to child/subview UIViewController (vc2) and in vc2 to vc1. Assign the references in parent(vc1) viewDidLoad() example below.

Parent UIViewController vc1:

      class vc1: UIViewController {

          @IBOutlet weak var parentLabel: UILabel!
          var childVc2: vc2?;

           overide func viewDidLoad() {
               super.viewDidLoad();
               // Use childViewControllers[0] without type/class verification only 
               // when adding a single child UIViewController 
               childVc2 = self.childViewControllers[0] as? vc2;
               childVc2?.parentVc1 = self
           }
      }

Child UIViewController vc2:

      class vc2: UIViewCortoller {
          var parentVc1: vc1?;

          // At this point child and parent UIViewControllers are loaded and 
          // child views can be accessed
          override func viewWillAppear(_ animated: Bool) {
             parentVc1?.parentLabel.text = "Parent label can be edited from child";
          }
      } 

In the Storyboard remember to set in Identity Inspector the parent UIViewContoller class to vc1 and child UIViewContoller class to vc2. Ctrl+drag from Container View in vc1 UIViewController to vc2 UIViewController and select Embed.

Matt
  • 399
  • 3
  • 6