自定义iOS 7导航栏左侧回退按钮

2014-08-27 Xiaosong Gao 更多博文 » 博客 » GitHub »

iOS

原文链接 https://gaoxiaosong.github.io/2014/08/27/custom-left-navi-back-button.html
注:以下为加速网络访问所做的原文缓存,经过重新格式化,可能存在格式方面的问题,或偶有遗漏信息,请以原文为准。


在iOS 7及以上的系统中,我们想自定义UINavigationController中UINavigationBar里面的回退按钮。

原来的回退按钮是一个红色的小于号箭头,而如果我们在UIViewController里面设置:

self.navigationItem.hidesBackButton = YES;

这样可以隐藏系统默认的回退按钮,然后自己按照如下代码添加左侧回退按钮:

self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navBack"]
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(onTapBackButton:)];

如此做法会添加自定义按钮,但是按钮的位置有些偏右,我们可以用如下方法来进行位置的调整:

UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
negativeSpacer.width = -20;
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navBack"]
                                                         style:UIBarButtonItemStylePlain
                                                        target:self
                                                        action:@selector(onTapBackButton:)];
[self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:negativeSpacer, item, nil]];

也就是说我们在左侧一共添加了两个按钮,最左面是一个固定宽度为-20的按钮,用来调整右面实际上的回退按钮的位置的。

当然,在导航栏右侧的按钮也可以用同样的方法进行调整位置。