无法在单独的视图控制器中更改UIBarButtonItem的背景

时间:2013-11-27 06:28:18

标签: ios objective-c uibarbuttonitem appearance

在我的appDelegate中:

UIImage *navBarArrowItemBackground = [UIImage imageNamed:@"tabbar_button_back"];
[UIBarButtonItem appearance] setBackButtonBackgroundImage:navBarArrowItemBackground
                                                          forState:UIControlStateNormal
                                                        barMetrics:UIBarMetricsDefault];

并在单独的视图控制器中:

UIBarButtonItem* backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self
                                                                      action:nil];
[backButton setBackgroundImage:[UIImage imageNamed:@"tabbar_button_back_gray"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self.navigationItem setBackBarButtonItem:backButton];

因此,在子视图控制器上,后退按钮的标题已更改,但背景取自appDelegate中的外观。我需要一个视图控制器的自定义背景。我该如何解决这个问题?

修改#1:

现在appDelegate看起来像这样:

UIImage *navBarArrowItemBackground = [UIImage imageNamed:@"tabbar_button_back"];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:navBarArrowItemBackground
                                                          forState:UIControlStateNormal
                                                        barMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearanceWhenContainedIn:[SettingsListViewController class], nil] setBackButtonBackgroundImage: [UIImage imageNamed:@"tabbar_button_back_gray"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

1 个答案:

答案 0 :(得分:1)

您可以通过在外观中添加约束来实现此目的:

[UIBarButtonItem appearanceWhenContainedIn:[YourOtherVC class], nil] setBackButtonBackgroundImage:navBarArrowItemBackground
                                  forState:UIControlStateNormal
                                barMetrics:UIBarMetricsDefault];

您的代码应如下所示:

UIImage *navBarArrowItemBackground = [UIImage imageNamed:@"tabbar_button_back"];
[[UIBarButtonItem appearanceWhenContainedIn:[SettingsListViewController class], nil] setBackButtonBackgroundImage: [UIImage imageNamed:@"tabbar_button_back_gray"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];