Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a parent view controller (through a navigationcontroller)

Currently I add a viewcontroller using pushViewController:animated: and now from within that new one would like to call a method inside my "parent"-controller. I think I get stuck at the navigationcontroller.

Currently trying this to see if it's the controller I want:

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 (a method in it) that pushed the current one?

like image 609
Pangolin Avatar asked Nov 08 '11 18:11

Pangolin


2 Answers

Just like Marsson mentioned, you need to use delegate...

Here is an sample:

In your child view controller .h file:

@protocol ChildViewControllerDelegate <NSObject>
- (void)parentMethodThatChildCanCall;
@end

@interface ChildViewController : UIViewController 
{
}
@property (assign) id <ChildViewControllerDelegate> delegate;

In your child view controller .m file:

@implementation ChildViewController
@synthesize delegate;


// to call parent method:
//  [self.delegate parentMethodThatChildCanCall];

In parent view controller .h file:

@interface parentViewController <ChildViewControllerDelegate>

In parent view controller .m file:

//after create instant of your ChildViewController
childViewController.delegate = self;

- (void) parentMethodThatChildCanCall
{
  //do thing
}
like image 197
user523234 Avatar answered Oct 14 '22 08:10

user523234


self.navigationController.viewControllers

Returns an array of all the view controllers in the navigation stack. The current view controller is at the top of the stack, the previous view controller is the next one down, and so forth.

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 what class the previous controller is you can cast it explicity instead of using id.

like image 34
jrturton Avatar answered Oct 14 '22 07:10

jrturton