简体   繁体   English

无需拉伸即可替换导航栏后退按钮

[英]Replace Navigation bar back button without stretching

I'm trying to replace the default nav bar back button image: 我正在尝试更换默认导航栏后退按钮图像:

UIImage *backButtonImage = [UIImage imageNamed:@"back_button"] ;

backButtonImage = [backButtonImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backButtonImage.size.width, 0, 0)];

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage
                                                  forState:UIControlStateNormal
                                                barMetrics:UIBarMetricsDefault];

What I get is this: 我得到的是这个: 在此输入图像描述

What I want is this: 我想要的是这个: 在此输入图像描述

How? 怎么样? The original image is 11x44 points. 原始图像是11x44点。

EDIT: After applying this, 编辑:申请后,

[UINavigationBar appearance].backIndicatorImage = backButtonImage;
[UINavigationBar appearance].backIndicatorTransitionMaskImage = backButtonImage;

I get this: 我明白了: 在此输入图像描述

I've spent hours trying to get the arrow to move down so that it's vertically aligned with the title text in the navigation bar, to no avail. 我花了好几个小时试图让箭头向下移动,以便它与导航栏中的标题文本垂直对齐,但无济于事。 I've seen other threads with the same problem, but no solution. 我见过其他线程有同样的问题,但没有解决方案。 Why would this be so difficult? 为什么这么难? It seems like something everyone who replaces the back button image would have to deal this. 似乎每个人都替换后退按钮图像必须处理这个问题。

Try this code : 试试这段代码:

UIImage *backBtnIcon = [UIImage imageNamed:@"backNavIcon.png"];

if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)) {
    [UINavigationBar appearance].backIndicatorImage = backBtnIcon;
    [UINavigationBar appearance].backIndicatorTransitionMaskImage = backBtnIcon;
}
else{
UIImage *backButtonImage = [backBtnIcon resizableImageWithCapInsets:UIEdgeInsetsMake(0, backBtnIcon.size.width - 1, 0, 0)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage  forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -backButtonImage.size.height*2) forBarMetrics:UIBarMetricsDefault];
}

Don't forget to put the 3 images 1x, @2x and @3x in your image assets. 不要忘记将3张图像1x,@ 2x和@ 3x放在图像资源中。

Please check the UIElements at apple document for back button. 请查看苹果文档中的UIElements以获取后退按钮。

Thanks! 谢谢!

您可以使用基于@“back_button”图像的CGContextRef创建一个新的UIImage,在其右侧绘制一个1点宽度的透明空间,这样就可以调用resizableImageWithCapInsets:UIEdgeInsetsMake(0, backButtonImage.size.width - 1, 0, 0)

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

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