項(xiàng)目中可能某些頁(yè)面返回按鈕需要自定義,然后在點(diǎn)擊返回按鈕時(shí)做出某些判斷,或者直接pop到根控制器,這時(shí)候需要禁用側(cè)滑返回手勢(shì),防止它不走判斷的代碼直接返回上個(gè)界面。
網(wǎng)上找了些資料,大致方法有兩種,但要注意的點(diǎn)沒(méi)有提到,容易出錯(cuò),這里整理下:
需求:A -> B -> C,要求B頁(yè)面禁用側(cè)滑返回
1. B push到 C,C頁(yè)面可以側(cè)滑返回;
2. B pop回 A,再?gòu)腁 push D,D要可以側(cè)滑返回。
方法一:
在B頁(yè)面的生命周期設(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è)滑手勢(shì),不要在viewWillAppear中設(shè)置!
如果在viewWillAppear中禁用了手勢(shì),你會(huì)發(fā)現(xiàn)B->C之后,在C界面?zhèn)然祷貢r(shí),APP會(huì)進(jìn)入假死狀態(tài)。原因是B界面將要出現(xiàn)時(shí),你禁用了側(cè)滑手勢(shì),導(dǎo)致C側(cè)滑失敗,界面卡住。所以要在B界面出現(xiàn)之后,再禁用側(cè)滑手勢(shì)。
2、要在viewWillDisappear里面激活導(dǎo)航的側(cè)滑手勢(shì),不是viewDidDisappear!
導(dǎo)航是共用的,如果不激活就返回了,其他頁(yè)面也將無(wú)法側(cè)滑返回!而在viewDidDisappear設(shè)置激活是無(wú)效的,要在頁(yè)面即將消失時(shí)激活。
方法二:
也是在B頁(yè)面的生命周期設(shè)置如下代碼。方法一是直接關(guān)閉和激活側(cè)滑手勢(shì),方法二則是B遵循協(xié)議UIGestureRecognizerDelegate,設(shè)置側(cè)滑交互代理,重寫手勢(shì)方法。
@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è)滑手勢(shì)代理:
我們有時(shí)候會(huì)自定義UINavigationController基類,里面可能已經(jīng)設(shè)置了側(cè)滑手勢(shì)代理,所以在B界面出現(xiàn)后我們重新設(shè)置代理為B,消失前我們要把代理重新改回為原來(lái)的。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注