iOS開發—向右滑動手勢實現返回


在navigationController中實現向右滑動返回功能

系統提供的backbarbuttonitem,不用添加任何代碼即可實現向右滑動后退功能,但是往往要對按鈕修改樣式等時,就需要自定義leftbarbuttonitem,此時向右滑動即失效.通過下面方法即可解決該問題.

主要是通過設置navigationController.interactivePopGestureRecognizer 

UIGestureRecognizerDelegate

1. self.navigationController.interactivePopGestureRecognizer.enabled = YES | NO;      手勢有效與否

2. self.navigationController.interactivePopGestureRecognizer.delegate = self;               手勢的代理,一般會設置為self

1中的屬性,再viewcontroller中默認的設置為YES,即手勢有效.按照2中的屬性設置后,當前的viewcontroller即可以實現該向右滑動后退功能,但是當回到navigationController的rootView中再次做出向右滑動時,程序會有問題(再次push子controller時,程序卡在當前界面無法跳轉).有效解決方案如下:

說明:有兩個controllerA,B

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

- (void)viewDidAppear:(BOOL)animated

{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;    //讓rootView禁止滑動
    }
}

然后再B中的- (void)viewDidLoad方法中加入

- (void)viewDidLoad

{
    // 配置返回按鈕
    UIBarButtonItem * backItem = [self barButtonForImageNames:@[@"icon-返回", @"", @""] action:@selector(popBack)];
    backItem.title = @"";
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    self.navigationItem.leftBarButtonItem = backItem;
}

這樣即可以保證再A中向右滑動后再次pushB時不會卡在A界面.

再項目中大家一般會創建風格統一的界面,一般都會創建一個基礎viewcontroller,再此viewcontroller擴展一個配置leftbarbutton的方法,在該方法中加入B的viewDidLoad中的代碼,這樣在創建leftbarbutton的同時,直接加了返回的操作(不用每個viewController中都加入這樣一段代碼).然后只在navigationController的rootView中加入A的(void)viewDidAppear:(BOOL)animated方法即可.

 


免責聲明!

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



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