How to change background image for navigation item(button)?

北慕城南 提交于 2019-12-11 08:57:45

问题


I want to set background image for every navigation item(button) (universal).

How should these images look?

Are there fixed dimensions or it is possible to create repeating background image?

How to programmatically change then this background image?

Thank's for help

UPDATE:

I found this code for changing background of this button but it's no working.

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

And I don't know which dimensions should be.

P.S. I want to change background of button just like you can change background color (self.navigation.controller.nvigationBar.tintColor..)


回答1:


The code below might solve your problem

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;



回答2:


u need to create Custom Back Button i m afraid

check this code out

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

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

Let me know if it worked

Cheers




回答3:


what about categories? For example, you can do so:

@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;
}


来源:https://stackoverflow.com/questions/10461004/how-to-change-background-image-for-navigation-itembutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!