如何更改背景图片的导航项目(按钮)?(How to change background image

2019-10-16 16:19发布

我想设置背景图片为每个导航项目(按钮)(通用)。

这些图片应该是什么样子?

是否有固定的尺寸,或者可以创建重复的背景图片?

如何以编程方式更改那么这个背景图片?

感谢帮助

更新:

我发现这个代码改变这个按钮的背景,但它没有工作。

UIImage *barButton = [UIImage imageNamed:@"button_background.png"];
    [[UIBarButtonItem appearance] setBackgroundImage:barButton forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

我不知道哪个尺寸应。

PS我想更改按钮,就像你可以改变背景颜色的背景(self.navigation.controller.nvigationBar.tintColor ..)

Answer 1:

下面的代码可能会解决你的问题

UIButton *backBtn     = [UIButton buttonWithType:UIButtonTypeCustom];  
UIImage *backBtnImage = [UIImage imageNamed:@"button_background.png"]  ;  
[backBtn setBackgroundImage:backBtnImage forState:UIControlStateNormal];  
[backBtn addTarget:self action:@selector(goback) forControlEvents:UIControlEventTouchUpInside];  
backBtn.frame = CGRectMake(0, 0, 54, 30);  
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn] ;  
self.navigationItem.leftBarButtonItem = cancelButton;


Answer 2:

u需要创建自定义后退按钮我怕

检查这个代码出

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] 
                               initWithImage:[UIImage imageNamed:@"yourImage.png"]
                                       style:UIBarButtonItemStyleBordered 
                                      target:nil 
                                      action:nil];

self.navigationItem.backBarButtonItem = backButton;
[backButton release];

让我知道它的工作

干杯



Answer 3:

什么类别? 例如,你可以这样做:

@interface UIBarButtonItem(JFAdditions)

- (id)initWithTitle:(NSString *)title image:(UIImage*)img;//add target and action if need

@end

 @implementation UIBarButtonItem(JFAdditions)

 - (id)initWithTitle:(NSString *)title image:(UIImage*)img
 {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //add background image and text on button, target and action if need, also
    self = [self initWithCustomView:btn];

    return self;
}


文章来源: How to change background image for navigation item(button)?