chongzixin
chongzixin

Reputation: 1981

Container View Controller delegate assignment

I have a parent view controller with two embedded controllers which I linked up using Storyboard. I am trying to allow communication among the ViewControllers by using delegates.

The problem is, I am stuck at trying to assign the delegate because I dont have a reference of my ChildViewController in the parent. Basically, I am looking for somewhere in ParentViewController.m to insert the code

ChildViewController.delegate = self;

I tried creating IBOutlets for each of the ChildViewControllers but I cant seem to assign them properly in the Storyboard.

Upvotes: 4

Views: 3598

Answers (1)

rdelmar
rdelmar

Reputation: 104082

There are a couple of ways to do this. In code you can get a reference to the child view controllers with self.childViewControllers, which gives you an array of all the children. The preferred way, is probably to use prepareForSegue:sender:. This will be called when the parent controller is instantiated, and you can get a reference to the child with segue.destinationViewController. Give each of the embed segues identifiers so you can know which segue is calling prepareForSegue. Someething like this:

@interface ViewController ()
@property (strong,nonatomic) UIViewController *topController;
@property (strong,nonatomic) UIViewController *bottomController;
@end

@implementation ViewController


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"topEmbed"]) {
        self.topController = segue.destinationViewController;
    }else if ([segue.identifier isEqualToString:@"bottomEmbed"]){
        self.bottomController = segue.destinationViewController;
    }
}

Upvotes: 11

Related Questions