I got a NavigationController(short for nv) and a ViewController(short for vc).
nv's RootViewController is vc.
I just want to set the NavigationItem , I want the left bar button to be BACK button(customized).since this left button shared in all ViewControllers so I don't want to write the code in the ViewController , otherwise I have to write it many times. And I can't just subclass a ViewController, since I only need my customized left bar item in just a few ViewController.
So I try adding the generating button code in my nv , but i failed.
The result is , only the original vc got customized left bar button. other vc which is push on it all got the default one.
Here is my NavigationController's code:
- (void) viewWillAppear:(BOOL)animated{
[self createBackButton];
- (void) createBackButton{
UIViewController* vc = [self.viewControllers lastObject];
vc.navigationItem.leftBarButtonItem = nil;
vc.navigationItem.leftBarButtonItem =
[[UIBarButtonItem alloc]initWithTitle:@"Roll Back"
style:UIBarButtonItemStyleBordered
target:self
action:backButtonPressedSelector];
}
But if I put my createBackButton method in my ViewController , everything works just fine. But I also Have to write this method many times. Even the sentence like [self createBackButton]
it seems that viewWillAppear isn't a good time to call my createBackButtonMethod
In what order does the method below be called when I am pushing and hoping view controller , and where should I add my createBackButtonMethod in order to got some of the ViewController have the same left bar button without writing unnecessary code?
1、NavigationController's didload
2、NavigationController's willappear
3、ViewController(the one being pushed) 's didload
4、ViewController's willappear
The the method calling order is this:
1、vc's didload
2、nv's didload
3、nv's will appear
4、vc's will appear
and then when I continue to push vc, there are only
vc's didload and vc'didload being called repeatedly.
That's why I failed, because the nv's didload will only be called once here.
Instead of writing a common parent class, I think of the pretty solution below.
So I override my pushViewController: method
- (void) pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
viewController.navigationItem.leftBarButtonItem = nil;
viewController.navigationItem.leftBarButtonItem =
[[UIBarButtonItem alloc]initWithTitle:@"Roll Back"
style:UIBarButtonItemStyleBordered
target:self
action:backButtonPressedSelector];
}
try to make parent view controller and extend all your view controllers from it and add the needed code in there all the view controller will have it
hope i understand your question right and this answer help you with your problem good luck