iOS 5: How to implement a custom (image) back button

好久不见. 提交于 2019-12-02 19:32:15

Assuming that your current solution

UIImage *backButtonHomeImage = [[UIImage imageNamed:@"backButtonHomeWhite_30.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonHomeImage  forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

is acceptable to you, so the only problem left is how to update that button appeareance when you go back and forth between your views, an approach that could work is executing the code above in each of your controllers' viewWillAppear: method:

- (void)viewWillAppear:(BOOL)animated {
    UIImage *backButtonHomeImage = [[UIImage imageNamed:@"backButtonHomeWhite_30.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonHomeImage  forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
}

If you are not satisfied with your current approach to having a custom UIBarButtonItem, the way to go is initializing your bar button item with initWithCustomView:. In this case, you can specify, e.g., a UIImageView with the image you like and it should work:

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:[UIImageView ...]];

Hope this helps.

For iOS 5+ use [[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:@"someimage.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault].

Some code i used in a project:

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *btnImg = [UIImage imageNamed:@"ButtonRetourInactive"];
[btn setImage:btnImg forState:UIControlStateNormal];

btn.frame = CGRectMake(0, 0, btnImg.size.width, btnImg.size.height);
[btn addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:btn] autorelease];

Note, this works on iOS 4 and 3 aswell.

if You are using story boards , its too easy . take a round rectangular button and place it on the navigation bar . then double click the button( on selecting,at first, it just shows attributes of bar button , but by selecting twice , you can change all its properties as if you are customizing a regular UI button) .

UIAppearance is no use in this case.

I tried to use: - [UIBarButtonItem initWithCustomView:]. The view here you can add your background image and title, whatever you want.

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