简体   繁体   中英

Can't change the background for UIBarButtonItem in a separate View Controller

in my appDelegate:

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

and in separate view controller:

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

So on the child view controllers the title of the back button is changed but the background is taken from the appearance in appDelegate. I need a custom background for one view controller. How can I solve this?

edit#1:

now appDelegate looks like this:

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

You can achieve this by adding constraint to the appearence as follows:

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

Your code should be look like as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM