Can't change the background for UIBarButtonItem

343 views Asked by At

I need to change the default (which was already declared in my AppDelegate) background for UIBarButtonItem in one ViewController.

So, In my AppDelegate I have:

UIImage *navBarItemBackground = [UIImage imageNamed:@"navbar_button_green"];
[[UIBarButtonItem appearance] setBackgroundImage:navBarItemBackground
                                            forState:UIControlStateNormal
                                               style:UIBarButtonItemStyleBordered
                                          barMetrics:UIBarMetricsDefault];

And when I need to restore the default background for the button - I implement in my viewController:

self.navigationItem.rightBarButtonItem = nil;
UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"Сохранить" style:UIBarButtonItemStyleBordered target:self action:@selector(clickOnSend:)];
[rightBarItem setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal style:UIBarButtonItemStyleBordered barMetrics:UIBarMetricsDefault];
self.navigationItem.rightBarButtonItem = rightBarItem;

But I think that it's not correct to set the empty file as the image. Is there more simple way to implement this behaviour? Thanks!

2

There are 2 answers

3
chancyWu On BEST ANSWER

If you want to change only one or several UIViewController's UIBarButtonItems backgroundImage, you'd better change in the specific UIViewControllers as the latter case you use. while [[UIBarButtonItem appearance] setBackgroundImage:forState:style:barMetrics:]; will change all the UIBarButtonItems background image, which maybe not the better one.

2
Nikos M. On

You should change your code to this:

UIBarButtonItem * rightBarItem = [[UIBarButtonItem alloc]
                                           initWithTitle: @"Сохранить"
                                           style: UIBarButtonItemStyleBordered
                                           target: nil action: nil];
UIImage *navBarItemBackground = [[UIImage imageNamed:@"navbar_button_green"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 6)];
[[UIBarButtonItem appearance] setBackgroundImage:navBarItemBackground
                                                forState:UIControlStateNormal
                                              barMetrics:UIBarMetricsDefault];

[self.navigationItem setBackBarButtonItem: rightBarItem];