无法更改UIBarButtonItem的背景

时间:2013-12-16 08:08:20

标签: ios objective-c uibarbuttonitem uiappearance

我需要在一个ViewController中更改UIBarButtonItem的默认值(已在我的AppDelegate中声明)背景。

所以,在我的AppDelegate中我有:

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

当我需要恢复按钮的默认背景时 - 我在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;

但我认为将空文件设置为图像是不正确的。是否有更简单的方法来实现此行为?谢谢!

2 个答案:

答案 0 :(得分:1)

如果您只想更改一个或多个UIViewController's UIBarButtonItems backgroundImage,您最好更改特定UIViewController s,因为您使用的是后一种情况。虽然[[UIBarButtonItem appearance] setBackgroundImage:forState:style:barMetrics:];会更改所有UIBarButtonItems背景图片,但这可能不是更好的背景图片。

答案 1 :(得分:0)

您应该将代码更改为:

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];