iOS左滑手势失效
iOS左滑手勢(shì)失效
iOS7之后,蘋果優(yōu)化了一個(gè)小功能,就是對(duì)于UINavagationController堆棧里的UIViewController,只要輕輕在視圖控制器的左邊緣右滑一下,該視圖控制器就會(huì)pop出棧(前提當(dāng)然是對(duì)于非根視圖控制器而言)。實(shí)現(xiàn)方法很簡(jiǎn)單,一句話搞定:
self.navigationController.interactivePopGestureRecognizer.enabled = YES;事實(shí)上對(duì)于一個(gè)視圖控制器而言,該屬性的默認(rèn)值即為YES,因此不設(shè)置也能實(shí)現(xiàn)右滑pop的功能。
然而這個(gè)功能很有局限性,因?yàn)樗辉试S當(dāng)前視圖控制器自定義了leftBarButtonItem,一旦自定義,右滑功能就會(huì)失效。這里有一個(gè)方法:
self.navigationController.interactivePopGestureRecognizer.delegate = nil;設(shè)置代理為nil之后即便自定義了leftBarButtonItem也可以右滑pop。
或者,把手勢(shì)的許可打開 也可:
self.navigationController.interactivePopGestureRecognizer.enabled = YES ;事實(shí)上如果自定義了leftBarButtonItem,常用的做法是重新設(shè)置代理:
- (void)viewDidAppear:(BOOL)animated{self.navigationController.interactivePopGestureRecognizer.delegate = (id)self; }然后實(shí)現(xiàn)手勢(shì)協(xié)議即可:
#pragma mark - UIGestureRecognizerDelegate - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer{//判斷是否為rootViewControllerif (self.navigationController && self.navigationController.viewControllers.count == 1) {return NO;}return YES; }不過呢,如果我們自定義的返回button只是文字或圖片的話,這樣設(shè)置就可以,不會(huì)失效
UIBarButtonItem *item = [[UIBarButtonItem alloc]init];item.title = @"";self.navigationItem.backBarButtonItem = item;如果是要自定義view的當(dāng)作button的話,就要用leftBarButtonItem設(shè)置,并用上述講的防止手勢(shì)失效的方案.
有朋友提出以上方式在多次滑動(dòng)之后會(huì)導(dǎo)致界面假死,這里再給出一種解決方案:
在所有除一級(jí)頁面之外的頁面的viewDidAppear和viewWillDisappear中加入以下代碼:
- (void)viewWillDisappear:(BOOL)animated {[super viewWillDisappear:animated];//代理置空,否則會(huì)閃退if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil;} } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; //開啟iOS7的滑動(dòng)返回效果 if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { //只有在二級(jí)頁面生效 if ([self.navigationController.viewControllers count] == 2) { self.navigationController.interactivePopGestureRecognizer.delegate = self; } } }在UINavigationController的delegate中實(shí)現(xiàn)以下方法:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated { //開啟滑動(dòng)手勢(shì)if ([navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {navigationController.interactivePopGestureRecognizer.enabled = YES;} }在pushviewcontroller之前加入以下代碼:
//在切換界面的過程中禁止滑動(dòng)手勢(shì),避免界面卡死 if ([_currentNav respondsToSelector:@selector(interactivePopGestureRecognizer)]) {_currentNav.interactivePopGestureRecognizer.enabled = NO; } [_currentNav pushViewController:viewController animated:YES];即可在實(shí)現(xiàn)滑動(dòng)返回的同時(shí),避免界面卡死的問題。
posted @ 2016-11-13 14:59 洛洛愛吃肉 閱讀( ...) 評(píng)論( ...) 編輯 收藏總結(jié)
- 上一篇: 科维的时间管理法—《可以量化的管…
- 下一篇: 条形的码