美文网首页iOS学习专题iOS
iOS开发技巧-捕捉侧滑返回事件

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

作者: Pandakingli | 来源:发表于2018-07-19 15:05 被阅读35次

    有时候希望在页面退出之前做一些事情,但是发现除了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(@"离开页面");   }
    }
    

    相关文章

      网友评论

        本文标题:iOS开发技巧-捕捉侧滑返回事件

        本文链接:https://www.haomeiwen.com/subject/wgjtmftx.html