自定義導航欄返回按鈕導致返回手勢失效問題

weixin_33890499發表於2017-05-30

需要注意的是手勢代理物件的儲存於轉交問題!!!
UIGestureRecognizerDelegate

自定義無法實現手勢效果圖 Gif

2932245-b5fc6220efa34630.gif
自定義無法實現手勢效果圖 Gif

自定義實現手勢效果圖 Gif

2932245-13ec8576fc5b5dfa.gif
自定義實現手勢效果圖 Gif

ViewController.m

#import "ViewController.h"
#import "NextViewController.h"

@interface ViewController ()


@end

@implementation ViewController 

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
}


- (IBAction)goToNextVC:(id)sender {
    NextViewController *nextVC = [[NextViewController alloc] init];
    [self.navigationController pushViewController:nextVC animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end

NextViewController.m

#import "NextViewController.h"

@interface NextViewController () <UIGestureRecognizerDelegate>

//變數用來儲存代理:
@property (nonatomic, strong) id<UIGestureRecognizerDelegate> originDelegate;

@end

@implementation NextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //自定義UIBarButtonItem 雖然滿足了 UI 的效果,但是卻導致了左側邊緣滑動失效,得不償失!
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"imgBack"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction)];
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    
    //側滑返回互動手勢:UIGestureRecognizer *interactivePopGestureRecognizer
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
}

//返回上一頁:
- (void)leftBarButtonItemAction {
    [self.navigationController popViewControllerAnimated:YES];
    
}


//檢視已經出現的時候,讓成員變數 originDelegate 儲存 導航控制器的互動返回手勢識別的代理:
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.originDelegate = self.navigationController.interactivePopGestureRecognizer.delegate;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
}


//當檢視將要消失的時候再把剛剛儲存的導航控制器的互動返回手勢識別代理變數重新置為系統自身的!
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.delegate = self.originDelegate;
    self.originDelegate = nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end

願程式設計讓這個世界更美好

相關文章