在UINavigationBar上为后退按钮设置自定义图像 [英] Setting a Custom Image for a Back Button on UINavigationBar

查看:125
本文介绍了在UINavigationBar上为后退按钮设置自定义图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为后退按钮设置自定义图像,当新视图被压入堆栈时,该按钮会自动放置到导航栏上。

I am trying to set a custom image for the back button that automatically gets place onto a navigation bar when a new view is pushed onto the stack.

我尝试在父viewController的viewDidLoad中添加以下内容:

I have tried adding the following in the viewDidLoad of the parent viewController:

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:@"BackButton.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

我也试过以下内容:

UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"BackButton.png"] style:UIBarButtonItemStyleBordered target:nil action:nil];
    self.navigationItem.backBarButtonItem = btn;

使用UIAppearance会产生非常奇怪的结果:

Using UIAppearance produces quite strange results:

推荐答案

试试这段代码

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

然后像这样定义goback方法

then define goback method like this

- (void)goback
{
    [self.navigationController popViewControllerAnimated:YES];
}

这篇关于在UINavigationBar上为后退按钮设置自定义图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆