iOS自定制导航栏返回按钮或者隐藏导航栏pop手势失效解决方案

在iOS开发的工做当中,Push和Pop常常用于界面之间的跳转和返回。苹果在iOS7之后给导航控制器加了一个Pop手势,只要手指在屏幕边缘滑动,当前的控制器的视图就会随着你的手指移动,当用户松手后,系统会判断手指拖动出来的大小来决定是否要执行控制器的pop操做。

      这个想法很是棒,可是系统给咱们规定手势触发的范围必须是屏幕左侧边缘,还有若是咱们自定制了返回按钮或者隐藏了导航栏,也就是执行了下面两句话中的一句手势都会失效:代理

[self.navigationController setNavigationBarHidden:YES animated:YES];
对象

self.navigationItem.leftBarButtonItem = 自定制返回按钮;
开发

那么,咱们就来解决手势失效和手势触发范围小这两个问题:get

       ①解决失效的问题,很简单,一句话it

Object-C版:
io

self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
iOS开发

Swift版:   
select

navigationController?.interactivePopGestureRecognizer?.delegate = self
方法

       ②解决手势触发范围小,整个界面均可以触发这个手势,也能够解决第一个问题。im

      这样解决第一个问题的那一句代码就要去掉了,而后经过打印:

NSLog(@"%@", self.navigationController?.interactivePopGestureRecognizer);

能够看出self.navigationController?.interactivePopGestureRecognizer是一个UIScreenEdgePanGestureRecognizer,这样就不难理解为何触发范围只有左侧边缘了。

那么咱们解决的办法就是把这个UIScreenEdgePanGestureRecognizer禁用,而后本身建立一个UIPanGestureRecognizer,把这个手势给UIScreenEdgePanGestureRecognizer
的代理,请看具体代码:

Object-C版:

-(void)popGesture{

self.navigationController.interactivePopGestureRecognizer.enabled = NO;//禁用原来的手势

id target = self.navigationController.interactivePopGestureRecognizer.delegate;//得到pop代理管理对象

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:target action:@selector(popBack:)];//建立一个pan手势

pan.delegate = self;//设置代理

[self.view addGestureRecognizer:pan];//添加到self.view上

}

-(void)popBack:(UIPanGestureRecognizer *)pan {

[self.navigationController popViewControllerAnimated:YES];

}

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {

return YES;//这个方法必须返回YES,也能够不写这个方法,默认返回YES

}

在viewDidLoad里直接调用:  [self popGesture];  //OK~~~

Swift版:

func popGesture() {

navigationController?.interactivePopGestureRecognizer?.enabled = false

let target = navigationController?.interactivePopGestureRecognizer?.delegate

let pan = UIPanGestureRecognizer(target: target, action: #selector(self.popBack(_:)))

pan.delegate = self

view.addGestureRecognizer(pan)

}

func popBack(pan: UIPanGestureRecognizer){

 navigationController?.popViewControllerAnimated(true)

}

func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {

  return true

}

在viewDidLoad里直接调用popGesture()  //OK~~~

   在咱们平常开发时,因为常常用到,建议给UIViewController写一个Category,这样用起来就很方便了。