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

有时候希望在页面退出之前做一些事情,但是发现除了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(@"离开页面");   }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值