0

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?

rishi
  • 11,779
  • 4
  • 40
  • 59
Legnus
  • 159
  • 1
  • 2
  • 12

2 Answers2

3

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.

graver
  • 15,183
  • 4
  • 46
  • 62
  • 1
    Thank you for your answer! I used that for my custom Navigation controller to but i forgot to use it for my UIViewController... Thx again for the reminder ;) works perfectly! – Legnus Jul 03 '12 at 11:57
0

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

Just use [self.navigationItem setRightBarButtonItem:rightBarButtonItem];

Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56