iOS頁面右滑返回的實現方法總結


1.邊緣觸發的系統方法

  ①系統返回按鈕

   self.navigationController.interactivePopGestureRecognizer.enabled = YES;

 ②自定義返回按鈕

 1. self.navigationController.interactivePopGestureRecognizer.enabled = YES;             2. self.navigationController.interactivePopGestureRecognizer.delegate = self;

在viewDidLoad里面加入這兩行代碼,遵循UIGestureRecognizerDelegate協議,當前的viewcontroller即可以實現該向右滑動后退功能,但是當回到navigationController的rootView中再次做出向右滑動時,程序會有問題(再次push子controller時,程序卡在當前界面無法跳轉).有效解決方案如下:

說明:有兩個controllerA,B

navigationController的rootview設置為A,在A中點擊按鈕后push B.在A的 -(void)viewDidAppear:(BOOL)animated方法中加入self.navigationController.interactivePopGestureRecognizer.enabled = NO;

2.全屏觸發的自定義方法

2.1 自定義所有控制器的父類,在全屏范圍內添加右滑手勢,觸發返回事件。

  在viewDidLoad中,創建UIPanGestureRecognizer,並添加到導航欄控制器上。

- (void) viewDidLoad {
    [super viewDidLoad];

    //1.獲取系統interactivePopGestureRecognizer對象的target對象
    id target = self.navigationController.interactivePopGestureRecognizer.delegate;

    //2.創建滑動手勢,taregt設置interactivePopGestureRecognizer的target,所以當界面滑動的時候就會自動調用target的action方法。
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] init];
    [pan addTarget:target action:NSSelectorFromString(@"handleNavigationTransition:")];
    pan.delegate = self;

    //3.添加到導航控制器的視圖上
    [self.navigationController.view addGestureRecognizer:pan];

    //4.禁用系統的滑動手勢
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

在滑動開始的觸發事件中控制除了根視圖控制器以外的所有控制器執行右滑事件。

#pragma mark - 滑動開始觸發事件
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    //只有導航的根控制器不需要右滑的返回的功能。
    if (self.navigationController.viewControllers.count <= 1) {
        return NO;
    }

    return YES;
}

這種實現方法在一定程度上解決了問題,但有局限性。一是其觸發是在所有次級控制器上作用,若部分控制器不需要該功能無法取消手勢;二是在實際應用中可能導致手勢沖突或因手指右滑停止而再返回原頁面而引起錯誤或崩潰。

2.2 從底層入手,創建一個UINavigationController的分類(category),從根本上解決右滑返回的問題。

這一成果來自Github上forkingdog的開源項目,使用方法很簡單,只需在你的項目中導入UINavigationController+FDFullscreenPopGesture這一分類,編譯通過后即可實現全屏幕的右滑返回,若需在某一個頁面取消事件,只需要引入UINavigationController+FDFullscreenPopGesture.h文件,然后在viewDidLoad方法中設置self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO,並在上一個頁面的viewWillAppear方法中設置self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES,就可自如地控制各個頁面的右滑返回效果實現與否。這一方法穩定而簡便地解決了問題。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM