I am trying to add a custom UIBarButtonItem
to my navigationItem. This button will be available in all my view controllers. so instead of adding it to each viewDidLoad
method in each viewDidLoad
I am trying to add it in my application Delegate class in a seperate method that i will call in the viewDidLoad
method.
Here is my Code:
UIImage* image = [UIImage imageNamed:@"some-header-icon.png"];
CGRect frame = CGRectMake(0,0,image.size.width,image.size.height);
UIButton* hellBtn = [[UIButton alloc] initWithFrame:frame];
[hellBtn setBackgroundImage:image forState:UIControlStateNormal];
[hellBtn setShowsTouchWhenHighlighted:NO];
[hellBtn addTarget:self action:@selector(goToHell) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:hellBtn];
[self.nav.navigationController.navigationItem setRightBarButtonItem:rightBarButtonItem];
[hellBtn release];
[rightBarButtonItem release];
if I replace the same code blog in any viewDidLoad
of any viewController and change
[self.nav.navigationController.navigationItem setRightBarButtonItem:rightBarButtonItem];
By:
[self.navigationItem setRightBarButtonItem:rightBarButtonItem];
It works perfectly. Any Idea Why?
Create a subclass of UIViewController
for ex. UIViewControllerBase
, override viewDidLoad
method and inside it create your rightBarButtonItem
and set it. Then make all of your controllers inherit UIViewControllerBase
- simple OOP scenario.