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(@"離開頁面");   }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章