改变按钮背景图像

使用此方法更改后退导航按钮的标题和背景图像。 标题已更改但按钮保持黑色

- (void)viewDidLoad { [super viewDidLoad]; [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"topBarbackground.png"] forBarMetrics:UIBarMetricsDefault]; UIBarButtonItem *backButton = [UIBarButtonItem new]; [backButton setBackgroundImage:[UIImage imageNamed:@"backButton.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; [backButton setTitle:NSLocalizedString(@"Back", nil)]; [[self navigationItem] setBackBarButtonItem:backButton]; } 

这样做的正确方法是什么?

使用setImagesetBackButtonBackgroundImage因为setBackgroundImage无效:

 - (void)viewDidLoad { [super viewDidLoad]; [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"topBarbackground.png"] forBarMetrics:UIBarMetricsDefault]; UIBarButtonItem *backButton = [UIBarButtonItem new]; // Put the image inside the button [backButton setImage:[UIImage imageNamed:@"backButton.png"]; [backButton setTitle:NSLocalizedString(@"Back", nil)]; [[self navigationItem] setBackBarButtonItem:backButton]; } 

要么

 { [super viewDidLoad]; [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"topBarbackground.png"] forBarMetrics:UIBarMetricsDefault]; UIBarButtonItem *backButton = [UIBarButtonItem new]; // Use the image as the button (like custom button) [backButton setBackButtonBackgroundImage:[UIImage imageNamed:@"backButton.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; [backButton setTitle:NSLocalizedString(@"Back", nil)]; [[self navigationItem] setBackBarButtonItem:backButton]; } 
 UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom]; [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside]; backButton.frame = kBarBackButtonFrame; [backButton setExclusiveTouch:YES]; [backButton setBackgroundImage:[UIImage imageNamed:NAV_BAR_BACK_DEFAULT_BUTTON] forState:UIControlStateNormal]; [backButton setBackgroundImage:[UIImage imageNamed:NAV_BAR_BACK_DEFAULT_BUTTON] forState:UIControlStateHighlighted]; [backButton setBackgroundImage:[UIImage imageNamed:NAV_BAR_BACK_DEFAULT_BUTTON] forState:UIControlStateSelected]; [backButton setTitle:NSLocalizedString(@"Back", nil) forState:UIControlStateNormal]; backButton.titleLabel.font = [UIFont systemFontOfSize:kBarBackButtonTitleFontSize]; [backButton setTitleColor:kBackButtonTitleColor forState:UIControlStateNormal]; UIBarButtonItem *backButtonHolder = [[UIBarButtonItem alloc] initWithCustomView:backButton]; self.navigationItem.rightBarButtonItem = backButtonHolder; 

请记住,堆栈中的每个UIViewController都有自己的navigationItem,因此最好的解决方案是创建一个UIViewController子类,并且您使用的每个UIViewController都应该扩展前一个类。 我确信有更好的解决方案,但这是我使用的解决方案。

 - (void)popViewControllerWithAnimation { [self.navigationController popViewControllerAnimated:YES]; }