关于iOS导航栏返回按钮问题的解决方法

时间:2022-08-24 10:47:22

最近遇到一个关于导航栏返回按钮的问题,因为之前项目里面都是用的系统默认的返回按钮样式所以没有想过要去更改,后来有需要将返回按钮箭头旁边的文字去掉,同时将该返回按钮的点击事件重新定义。一开始尝试自定义按钮然后设置为leftbarbuttonitem,但是这样图片可能跟系统自带的不一样,还有就是返回按钮的位置跟系统自带的不一样。后来找了一些资料,发现将文字去掉比较简单,一般做法是控制器中添加如下代码,然后他的下一级控制就有一个只有箭头没有文字返回按钮:

 

复制代码 代码如下:
uibarbuttonitem *backbtn = [[uibarbuttonitem alloc] initwithtitle:@"" style:uibarbuttonitemstyleplain target:nil action:nil];
self.navigationitem.backbarbuttonitem = backbtn;


也可以创建一个根控制器在其中使用上述代码然后让其他控制器继承这个根控制器实现批量操作。但是如果遇到需要自定义该返回的点击事件的时候,在上面方法中添加target与action是不可行的,同时这种做法也会产生一个问题,就是实际的返回按钮点击区域总是比按钮看到的范围大,一般是距离箭头右边30距离都可点击。接下来我就带大家一起了解这些问题产生的原因以及如何更好的解决这些问题。

 

  首先我们看一下按照上面代码去掉返回按钮文字之后的导航栏视图的结构层次,因为导航栏的视图加载以及初始化跟viewcontroller的view不一样,不能再veiwdidload中去观察(viewwillappear中也不行)要在viewdidload中才可以看到完整的导航栏视图结构层次。我们可以在一个有去掉文字的返回按钮控制器的viewdidload中打上断点然后在控制台执行:

po [[uiwindow keywindow] recursivedescription]
会得到如下输出:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<uiwindow: 0x8d6f970; frame = (0 0; 320 480); autoresize = w+h; gesturerecognizers = <nsarray: 0x8d5dbf0>; layer = <uiwindowlayer: 0x8d717d0>>
 | <uilayoutcontainerview: 0x8d7bbf0; frame = (0 0; 320 480); autoresize = w+h; gesturerecognizers = <nsarray: 0x8d78a70>; layer = <calayer: 0x8d7bcd0>>
 | | <uinavigationtransitionview: 0x8d813f0; frame = (0 0; 320 480); clipstobounds = yes; autoresize = w+h; layer = <calayer: 0x8d814d0>>
 | | | <uiviewcontrollerwrapperview: 0x8d61050; frame = (0 0; 320 480); autoresize = w+h; userinteractionenabled = no; layer = <calayer: 0x8d88f40>>
 | | | | <uiview: 0x8ab0dc0; frame = (0 0; 320 480); autoresize = rm+bm; layer = <calayer: 0x8ab0610>>
 | | | | | <_uilayoutguide: 0x8ab0e20; frame = (0 0; 0 64); hidden = yes; layer = <calayer: 0x8ab0e90>>
 | | | | | <_uilayoutguide: 0x8ab1080; frame = (0 480; 0 0); hidden = yes; layer = <calayer: 0x8ab10f0>>
 | | <uinavigationbar: 0x8d75c40; frame = (0 20; 320 44); opaque = no; autoresize = w; userinteractionenabled = no; gesturerecognizers = <nsarray: 0x8d5e750>; layer = <calayer: 0x8d70f00>>
 | | | <_uinavigationbarbackground: 0x8d59af0; frame = (0 -20; 320 64); opaque = no; autoresize = w; userinteractionenabled = no; layer = <calayer: 0x8d549f0>> - (null)
 | | | | <_uibackdropview: 0x8d7c440; frame = (0 0; 320 64); opaque = no; autoresize = w+h; userinteractionenabled = no; layer = <_uibackdropviewlayer: 0x8d7e7b0>>
 | | | | | <_uibackdropeffectview: 0x8d7f1c0; frame = (0 0; 320 64); clipstobounds = yes; opaque = no; autoresize = w+h; userinteractionenabled = no; animations = { filters.colormatrix.inputcolormatrix=<cabasicanimation: 0x8ba4490>; }; layer = <cabackdroplayer: 0x8d7f480>>
 | | | | | <uiview: 0x8d7fc80; frame = (0 0; 320 64); hidden = yes; opaque = no; autoresize = w+h; userinteractionenabled = no; layer = <calayer: 0x8d7fce0>>
 | | | | <uiimageview: 0x8d67cc0; frame = (0 64; 320 0.5); userinteractionenabled = no; layer = <calayer: 0x8d67d50>> - (null)
 | | | <uinavigationitemview: 0x8ab6400; frame = (124 8; 163 27); opaque = no; userinteractionenabled = no; layer = <calayer: 0x8ab6480>>
 | | | | <uilabel: 0x8ab64b0; frame = (0 3; 163 22); text = 'a story about a fish'; clipstobounds = yes; opaque = no; userinteractionenabled = no; layer = <calayer: 0x8ab6550>>
 | | | <uinavigationitembuttonview: 0x8ab6c80; frame = (8 6; 41 30); opaque = no; userinteractionenabled = no; layer = <calayer: 0x8ab6d60>>
 | | | | <uilabel: 0x8ab6f10; frame = (-981 -995; 91 22); text = ''; clipstobounds = yes; opaque = no; userinteractionenabled = no; layer = <calayer: 0x8ab6fb0>>
 | | | <_uinavigationbarbackindicatorview: 0x8d87560; frame = (8 12; 12.5 20.5); opaque = no; userinteractionenabled = no; layer = <calayer: 0x8d87650>> - back

直接看或许不容易懂,还需要结合xcode的“debug view hierarchy”或者是reveal工具看实际视图结构:

关于iOS导航栏返回按钮问题的解决方法

我们可以看到在uinavigationbar中包含有4个类,它们大致的作用是:

_uinavigationbarbackground :(uiimageview)导航栏背景图(不可以直接设置图片)
uinavigationitemview :(uiview)包含显示导航栏标题
uinavigationitembuttonview :(uiview)包含显示导航栏左视图(不可移除,更改大小,颜色,可以隐藏,决定了点击区域的大小)
_uinavigationbarbackindicatorview :(uiimageview)导航栏返回按钮箭头图片(不可以修改图片)
_uinavigationbarbackindicatorview就是返回按钮的箭头也就是我们需要保留的,uinavigationitembuttonview就是我们需要研究的也是我们前面提到问题的主要原因所在。再次看看这个对象在控制台的输出:

?
1
2
| | | <uinavigationitembuttonview: 0x8ab6c80; frame = (8 6; 41 30); opaque = no; userinteractionenabled = no; layer = <calayer: 0x8ab6d60>>
| | | | <uilabel: 0x8ab6f10; frame = (-981 -995; 91 22); text = ''; clipstobounds = yes; opaque = no; userinteractionenabled = no; layer = <calayer: 0x8ab6fb0>>

这个uinavigationitembuttonview应该是系统在这个view的draw方法里就决定frame,修改frame就触发needdisplay重新改变它的frame,因此这个view只会根据其上的label(也就是返回按钮显示的文字)的内容变化而改变宽度其余基本不可变,我们虽然将label的内容设置为空但是这个uinavigationitembuttonview的大小却并没有改变同时点击区域也没有改变。从控制台里的还可看到这个veiw的userinteractionenabled属性为no,如果说点击的是这个view,但现在这个view是不可交互的,只能说明是真正响应点击事件的是这个view背后的某个控件(视图结构和代码里都没有发现这个控件)。因此要想解决我之前提到的问题就得利用这个uinavigationitembuttonview,我们可以在viewdidappear中取得到uinavigationitembuttonview(如果用遍历的方式获取会有一个延迟,因为这个view的位置固定为第三个所以我们就直接获取就可以了),将其userinteractionenabled设置为yes并且在这个view上添加手势tap事件即可:

?
1
2
3
4
5
6
7
8
9
10
uiview *nav_back = [self.navigationcontroller.navigationbar.subviews objectatindex:2];
if ([nav_back iskindofclass:nsclassfromstring(@"uinavigationitembuttonview")]) {
  nav_back.userinteractionenabled = yes;
  // uitapgesturerecognizer *tap = [[uitapgesturerecognizer alloc] initwithtarget:self action:@selector(backaction:)];
  // [nav_back addgesturerecognizer:tap];
  uibutton *backbutton = [uibutton buttonwithtype:uibuttontypecustom];
  backbutton.frame = cgrectmake(0, 0, 20, 21);
  [backbutton addtarget:self action:@selector(custommethod) forcontrolevents:uicontroleventtouchupinside];
  [nav_back addsubview:backbutton];
 }

这样可以改变返回按钮的点击事件,此时想要解决点击范围只能在这个view上添加一个指定大小的按钮了。最后总结出来的解决办法就是创建一个viewcontroller的分类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
uiviewcontroller+custombackbutton.h文件
 
#import <uikit/uikit.h>
 
@interface uiviewcontroller (custombackbutton)
 
- (void)customnavbackbuttonmethod;
 
@end
 
uiviewcontroller+custombackbutton.m文件
 
#import "uiviewcontroller+custombackbutton.h"
#import <objc/runtime.h>
 
@implementation uiviewcontroller (custombackbutton)
 
+ (void)load {
 static dispatch_once_t oncetoken;
 dispatch_once(&oncetoken, ^{
  class class = [self class];
  
  sel originalselector = @selector(viewdidload);
  sel swizzledselector = @selector(mm_viewdidload);
  
  sel originalselector1 = @selector(viewdidappear:);
  sel swizzledselector1 = @selector(mm_viewdidappear);
  
  method originalmethod = class_getinstancemethod(class, originalselector);
  method swizzledmethod = class_getinstancemethod(class, swizzledselector);
  
  method originalmethod1 = class_getinstancemethod(class, originalselector1);
  method swizzledmethod1 = class_getinstancemethod(class, swizzledselector1);
  
  bool didaddmethod = class_addmethod(class, originalselector, method_getimplementation(swizzledmethod), method_gettypeencoding(swizzledmethod));
  bool didaddmethod1 = class_addmethod(class, originalselector1, method_getimplementation(swizzledmethod1), method_gettypeencoding(swizzledmethod1));
 
  if (didaddmethod) {
   class_replacemethod(class, swizzledselector, method_getimplementation(originalmethod), method_gettypeencoding(originalmethod));
  } else {
   method_exchangeimplementations(originalmethod, swizzledmethod);
  }
  
  if (didaddmethod1) {
   class_replacemethod(class, swizzledselector1, method_getimplementation(originalmethod1), method_gettypeencoding(originalmethod1));
  } else {
   method_exchangeimplementations(originalmethod1, swizzledmethod1);
  }
 });
}
 
#pragma mark - method swizzling
 
- (void)mm_viewdidload {
 [self mm_viewdidload];
 uibarbuttonitem *backbuttonitem = [[uibarbuttonitem alloc] initwithtitle:@"" style:uibarbuttonitemstyleplain target:nil action:nil];
 [self.navigationitem setbackbarbuttonitem:backbuttonitem];
}
 
- (void)mm_viewdidappear {
 [self mm_viewdidappear];
 uiview *nav_back = [self.navigationcontroller.navigationbar.subviews objectatindex:2];
 if ([nav_back iskindofclass:nsclassfromstring(@"uinavigationitembuttonview")]) {
  nav_back.userinteractionenabled = yes;
  // uitapgesturerecognizer *tap = [[uitapgesturerecognizer alloc] initwithtarget:self action:@selector(backaction:)];
  // [nav_back addgesturerecognizer:tap];
  uibutton *backbutton = [uibutton buttonwithtype:uibuttontypecustom];
  backbutton.frame = cgrectmake(0, 0, 20, 21);
  [backbutton addtarget:self action:@selector(customnavbackbuttonmethod) forcontrolevents:uicontroleventtouchupinside];
  [nav_back addsubview:backbutton];
 }
}
 
 
- (void)customnavbackbuttonmethod {
 [self.navigationcontroller popviewcontrolleranimated:yes];
}
 
@end

在项目里面创建完以后就会生效。这里所做的就是在所有的viewcontroller执行viewdidload的时候将返回按钮的文字置空,在执行viewdidappear的时候添加一个自定义的按钮去响应pop事件。如果遇到需要自定义返回事件我在.h将返回事件开放出来,只要在对应的viewdidload中复写customnavbackbuttonmethod方法就可以在点击返回按钮时执行到你复写的方法中了,好了,是不是感觉很简单呢。