简体   繁体   English

UIBarButtonItem设计更改第一次无效,但第二次无效

[英]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: 我想更改我的UIBarButtonItem的设计,并且此代码有些起作用:

- (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. 若要使用UIAppearance ,应在加载视图或创建控件之前设置控件的外观。 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 . 或尝试在application didFinishLaunchingWithOptions设置外观。

From UIAppearance.h 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. 要为包含在容器类的实例中的类的实例或层次结构中的实例自定义外观,请对适当的外观代理使用+ appearanceWhenContainedIn:。 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];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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