简体   繁体   English

如何使用界面构建器更改UIBarButtonItem创建的背景图像

[英]How to change background image of UIBarButtonItem create with interface builder

I create a few UIBarButtonItem with interface builder and try to customize the button to green color. 我使用界面构建器创建了一些UIBarButtonItem,然后尝试将按钮自定义为绿色。 While I couldn't find ways to change background color of the button, I decide to code in this way: IBOutlet UIBarButtonItem *btnDone; 虽然我找不到改变按钮背景颜色的方法,但我决定以这种方式进行编码:IBOutlet UIBarButtonItem * btnDone;

-(void)viewDidLoad {
    [super viewDidLoad];

    UIImage *buttonImage = [[UIImage imageNamed:@"btnGreen.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [doneButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [doneButton setTitle:@"Done" forState:UIControlStateNormal];    
    [doneButton addTarget:self action:@selector(saveDateEdit:) forControlEvents:UIControlEventTouchUpInside];
    [doneButton.titleLabel setFont:[UIFont boldSystemFontOfSize:13]];
    doneButton.frame = CGRectMake(0.0, 0.0, 50, 30);
    btnDone = [[UIBarButtonItem alloc] initWithCustomView:doneButton];
    [doneButton release];
}

I create IBOutlet and link to the button from interface builder while I try to override this during it first load. 我创建了IBOutlet并从界面生成器链接到该按钮,而我尝试在首次加载时覆盖它。 However, it is showing the default button. 但是,它显示的是默认按钮。

Would like to know why is this happening? 想知道为什么会这样吗? Or even better someone can suggest me better way changing my UIBarButtonItem to green. 甚至更好的人可以建议我将UIBarButtonItem更改为绿色的更好方法。

Appreciate your help! 感谢您的帮助!

You are missing one point, 您遗漏了一点,

You are de-referring the btnDone object- as first you assign it using IBOutlet and then de-reffer by using btnDone = [[UIBarButtonItem alloc] init... ].. what you should do is add it programmatically instead of using IBOutlet . 您正在取消引用btnDone对象-首先使用IBOutlet对其进行分配,然后使用btnDone = [[UIBarButtonItem alloc] init... ] btnDone = [[UIBarButtonItem alloc] init... 。您应该做的是以编程方式添加它,而不是使用IBOutlet it will do your work. 它会做你的工作。

Thanks, 谢谢,

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

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