項(xiàng)目中可能某些頁面返回按鈕需要自定義,然后在點(diǎn)擊返回按鈕時做出某些判斷,或者直接pop到根控制器,這時候需要禁用側(cè)滑返回手勢,防止它不走判斷的代碼直接返回上個界面。
網(wǎng)上找了些資料,大致方法有兩種,但要注意的點(diǎn)沒有提到,容易出錯,這里整理下:
需求:A -> B -> C,要求B頁面禁用側(cè)滑返回
1. B push到 C,C頁面可以側(cè)滑返回;
2. B pop回 A,再從A push D,D要可以側(cè)滑返回。
方法一:
在B頁面的生命周期設(shè)置如下代碼
-(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled = NO; } } -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled = YES; }; }
注意:
1、是在viewDidAppear里面禁用導(dǎo)航的側(cè)滑手勢,不要在viewWillAppear中設(shè)置!
如果在viewWillAppear中禁用了手勢,你會發(fā)現(xiàn)B->C之后,在C界面?zhèn)然祷貢r,APP會進(jìn)入假死狀態(tài)。原因是B界面將要出現(xiàn)時,你禁用了側(cè)滑手勢,導(dǎo)致C側(cè)滑失敗,界面卡住。所以要在B界面出現(xiàn)之后,再禁用側(cè)滑手勢。
2、要在viewWillDisappear里面激活導(dǎo)航的側(cè)滑手勢,不是viewDidDisappear!
導(dǎo)航是共用的,如果不激活就返回了,其他頁面也將無法側(cè)滑返回!而在viewDidDisappear設(shè)置激活是無效的,要在頁面即將消失時激活。
方法二:
也是在B頁面的生命周期設(shè)置如下代碼。方法一是直接關(guān)閉和激活側(cè)滑手勢,方法二則是B遵循協(xié)議UIGestureRecognizerDelegate,設(shè)置側(cè)滑交互代理,重寫手勢方法。
@property (weak, nonatomic) id<UIGestureRecognizerDelegate> restoreInteractivePopGestureDelegate; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. _restoreInteractivePopGestureDelegate = self.navigationController.interactivePopGestureRecognizer.delegate; } -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.delegate = self; } } -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.delegate = _restoreInteractivePopGestureDelegate; }; } #pragma mark -UIGestureRecognizerDelegate -(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { return NO; }
這里主要解釋下為什么要記錄導(dǎo)航的側(cè)滑手勢代理:
我們有時候會自定義UINavigationController基類,里面可能已經(jīng)設(shè)置了側(cè)滑手勢代理,所以在B界面出現(xiàn)后我們重新設(shè)置代理為B,消失前我們要把代理重新改回為原來的。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選