Call the parent view controller (via the navigation controller)

I am currently adding a viewcontroller using pushViewController:animated: and now from inside this new one you want to call the method inside my "parent" controller. I think I'm stuck in the navigation controller.

You are currently trying to find out if I need a controller:

 if([self.superclass isKindOfClass:[MySuperController class]]) // and tried: if([self.presentingViewController isKindOfClass:[MySuperController class]]) 

None of these two worked.

How can I access the controller (the method in it) that pressed the current one?

+6
source share
3 answers

As Marson mentioned, you need to use a delegate ...

Here is an example:

In your child controller .h file:

 @protocol ChildViewControllerDelegate <NSObject> - (void)parentMethodThatChildCanCall; @end @interface ChildViewController : UIViewController { } @property (assign) id <ChildViewControllerDelegate> delegate; 

In your child controller .m file:

 @implementation ChildViewController @synthesize delegate; // to call parent method: // [self.delegate parentMethodThatChildCanCall]; 

In the controller's parent view, the .h file is:

 @interface parentViewController <ChildViewControllerDelegate> 

In the parent view of the dispatcher .m file:

 //after create instant of your ChildViewController childViewController.delegate = self; - (void) parentMethodThatChildCanCall { //do thing } 
+37
source
 self.navigationController.viewControllers 

Returns an array of all view controllers in the navigation stack. The current view controller is at the top of the stack, the previous view controller is the next, etc.

So you can do the following:

 NSArray *viewControllers = self.navigationController.viewControllers; int count = [viewControllers count]; id previousController = [viewControllers objectAtIndex:count - 2]; if ([previousController respondsToSelector:@selector(myMethod)]) [previousController myMethod]; 

If you know which class is the previous controller, you can use its explication instead of using id.

+4
source

Not sure about your application logic, but you can always do it.

In your "child" controller, declare a property of the parent type controller. So in your .h file:

 MySuperController *superController; property(nonatomic, retain)MysuperController *superController; 

and in your .m file:

 @synthesize superController; 

Before you "click" your child controller:

 MyChildController *child = ... [child setSuperController:self]; [self.navigationController pushViewController:child animated:YES]; 

Then in your child controller, you can just access your super with

 [this.superController myMethod:param]; 

I will not protect this encoding method, but it is a quick / cheap / dirty way to achieve something.

+1
source

Source: https://habr.com/ru/post/901055/


All Articles