dickfala dickfala - 3 months ago 32
iOS Question

iOS Container View and Parent ViewController communication?

How can I communicate with container view controller and parent view controller? I've tried to make a communication and pass the value between them. I've added a container view in the green view controller. And I had set segue name with "communicateSegue". I've searched some methods, I know we can set the prepareForSegue to pass the value at initial.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"communicateSegue"]) {
NSLog(@"call prepare for segue at parent view controller");
}
}


But now I want to pass value and change the label in the different viewcontroller . Not at the initial.

I don't know how to do?

Question:

Have anyone know how to implement ParentViewController pass value to Container View Controller and show the label in the ContainerViewController?

And reverse , Container View Controller click the button then pass the value and change the label show in the ParentViewController with objective-c?

Thanks.

My declare variable in parentViewController.h:
#import

@interface ParentViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *parentTF;
@property (weak, nonatomic) IBOutlet UIButton *passValToChildVCBtn;

@property (weak, nonatomic) IBOutlet UILabel *showContainerValLB;
@property (weak, nonatomic) IBOutlet IBAction *passValueToContainerEvent;

@end


In the ContainerChildViewController.h
#import

@interface ContainerChildViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *showParentValLB;
@property (weak, nonatomic) IBOutlet UITextField *childTF;
@property (weak, nonatomic) IBOutlet UIButton *passToParentBtn;
@property (weak, nonatomic) IBOutlet IBAction *passValueToParentBtnEvent;

@end


enter image description here

test project in the here.

thank you very much.

Answer

Regarding passing value to the containerView controller, you can make a property in the ChildViewController of the value you want it to be passed. Then in your ParentViewController do something like the following:

self.ChildViewController.yourProperty = yourValue

The opposite can be done in 4 ways:

  • You can make a delegate protocol to communicate the data between your controllers.
  • You can post a notification in your ChildViewController and add the parent controller as an observer.
  • You can use KVO.
  • And the easiest way out, you can make a property in your parentviewController and access it like the following

    ((YourParentViewControllerClassType *)self.parentViewController).yourParentProperty = TheValueYouWant;