简体   繁体   中英

UIBarButtonItem design change doesn't work the first time but the second

I want to change the design of my UIBarButtonItem and it works somewhat with this code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *image = [[UIImage imageNamed:@"header.png"]  resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
    [[UIBarButtonItem appearance] setBackgroundImage:image forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
}

The problem is that the first time the app loads the background image of the button doesn't change, but if I leave the view and come back the background is changed to what I want. What vould be the issue here? I use storyboards.

To work with UIAppearance you should set the appearance of the control before view is getting loaded or the control is created. If you are creating the control programmatically you can do like (sample code)

 [[UIStepper appearance]setTintColor:[UIColor redColor]];
 UIStepper *stepper = [[UIStepper alloc]init];
 [self.view addSubview: stepper];

or try to set the appearance in application didFinishLaunchingWithOptions .

From UIAppearance.h

To customize the appearances for instances of a class contained within an instance of a container class, or instances in a hierarchy, use +appearanceWhenContainedIn: for the appropriate appearance proxy. For example:

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:myNavBarColor];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], [UIPopoverController class], nil] setTintColor:myPopoverNavBarColor];
[[UIBarButtonItem appearanceWhenContainedIn:[UIToolbar class], nil] setTintColor:myToolbarColor];
[[UIBarButtonItem appearanceWhenContainedIn:[UIToolbar class], [UIPopoverController class], nil] setTintColor:myPopoverToolbarColor];

在初始化课程之前,请在您的课程之外调用代码。

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