Legnus
Legnus

Reputation: 159

How can i add a custom uibarbuttonItem to my navigation item in all view controllers?

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?

Upvotes: 0

Views: 541

Answers (2)

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

You should not use this self.nav.navigationController since nav is a UINavigationController then dont get the .navigationController

Just use [self.navigationItem setRightBarButtonItem:rightBarButtonItem];

Upvotes: 0

graver
graver

Reputation: 15213

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.

Upvotes: 3

Related Questions