[绍棠] 捕捉侧滑返回事件

// 官方文档

/*
  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(@"离开页面");   }
}
发布了179 篇原创文章 · 获赞 24 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/happyshaotang2/article/details/104918505