iOS开发技巧-捕捉侧滑返回事件

版权声明:本文为博主原创文章,未经博主允许不得转载。[email protected] 技术讨论群:536739494 https://blog.csdn.net/Nathan1987_/article/details/81115659

有时候希望在页面退出之前做一些事情,但是发现除了popViewController方法外,有时候会使用侧滑返回。这个时候就需要捕捉侧滑返回的事件了。

//普通的pop操作
[self.navigationController popViewControllerAnimated:YES];

//苹果的api说明 与侧滑返回相关

/*
  These two methods are public for container subclasses to call when transitioning between child controllers. 
If they are overridden, the overrides should ensure to call the super. The parent argument in
  both of these methods is nil when a child is being removed from its parent; otherwise it is equal to the new parent view controller.
 addChildViewController: will call [child willMoveToParentViewController:self] before adding the
  child. However, it will not call didMoveToParentViewController:. It is expected that a container view
  controller subclass will make this call after a transition to the new child has completed or, in the
  case of no transition, immediately after the call to addChildViewController:. Similarly,
  removeFromParentViewController does not call [self willMoveToParentViewController:nil] before removing the
  child. This is also the responsibilty of the container subclass. Container subclasses will typically define
  a method that transitions to a new child by first calling addChildViewController:, then executing a
  transition which will add the new child's view into the view hierarchy of its parent, and finally will call
  didMoveToParentViewController:. Similarly, subclasses will typically define a method that removes a child in
  the reverse manner by first calling [child willMoveToParentViewController:nil].
*/
- (void)willMoveToParentViewController:(nullable UIViewController *)parent NS_AVAILABLE_IOS(5_0);
- (void)didMoveToParentViewController:(nullable UIViewController *)parent NS_AVAILABLE_IOS(5_0);

在当前控制器中重写这两个方法就可以了。
1.第一次push进来的时候两个方法都会调用,parent的值不为空
2.当开始使用系统侧滑的时候,会先调用willMove,而parent的值为空
3.当滑动结束后返回了上个页面,则会调用didMove,parent的值也为空,如果滑动结束没有返回上个页面,也就是轻轻划了一下还在当前页面,那么则不会调用didMove方法。
想要在侧滑返回后在上个页面做一些操作的话,可以在didMove方法中根据parent的值来判断。

第一种情况,并没有返回

第二种情况,成功返回

- (void)willMoveToParentViewController:(UIViewController*)parent
{      
  [super willMoveToParentViewController:parent];      

  NSLog(@"%s,%@",__FUNCTION__,parent);

}

- (void)didMoveToParentViewController:(UIViewController*)parent
{  
        [super didMoveToParentViewController:parent];       

      NSLog(@"%s,%@",__FUNCTION__,parent);

    if(!parent){   NSLog(@"离开页面");   }
}

猜你喜欢

转载自blog.csdn.net/Nathan1987_/article/details/81115659
今日推荐