UINavigationBar:拦截后退按钮和后退滑动手势 [英] UINavigationBar: intercept back button and back swipe gesture
问题描述
我有一个UINavigationBar,它拦截后退按钮的点击,如果有未保存的更改,该按钮会警告用户.这基于 UINavigationController和UINavigationBarDelegate.ShouldPopItem()中提供的解决方案使用UINavigationBarDelegate协议并实现- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;
I have a UINavigationBar that intercepts the back button tap that alerts the user if there are unsave changes. This is based on the solution presented in UINavigationController and UINavigationBarDelegate.ShouldPopItem() with MonoTouch using the UINavigationBarDelegate protocol and implementing - (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;
现在,iOS7引入了滑动后退手势,我也想对其进行拦截,但无法使其与我到目前为止找到的解决方案配合使用,即使用[self.interactivePopGestureRecognizer addTarget:self action:@selector(handlePopGesture:)];
和
Now, iOS7 has introduced the swipe-to-go-back gesture, and I'd like to intercept that as well, but can't get it to work with the solutions I've found so far, namely using [self.interactivePopGestureRecognizer addTarget:self action:@selector(handlePopGesture:)];
and
- (void)handlePopGesture:(UIGestureRecognizer *)gesture {
if (gesture.state == UIGestureRecognizerStateEnded) {
[self popViewControllerAnimated:NO];
}
}
虽然这确实会弹出视图,但它会将导航栏按钮保留在原处,所以我最后得到的是无处可退的后退按钮,以及我添加到导航栏中的所有其他导航按钮.有提示吗?
While this does pop the views, it leaves the navigation bar buttons in place, so I'm ending up with a back button that leads nowhere, as well as all other navigation button I've added to the nav bar. Any tips?
推荐答案
要拦截向后轻扫手势,可以将self
设置为手势的代表(<UIGestureRecognizerDelegate>
),然后从gestureRecognizerShouldBegin
返回YES或NO.基于未保存的更改:
To intercept the back swipe gesture you can set self
as the delegate of the gesture (<UIGestureRecognizerDelegate>
) and then return YES or NO from gestureRecognizerShouldBegin
based on unsaved changes:
// in viewDidLoad
self.navigationController.interactivePopGestureRecognizer.delegate = self;
// ...
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
if ([gestureRecognizer isKindOfClass:[UIScreenEdgePanGestureRecognizer class]]) {
if (self.dirty) {
// ... alert
return NO;
} else
return YES;
} else
return YES;
}
在警报中,您可以询问用户是否仍要返回,在这种情况下,请在alertView clickedButtonAtIndex:
In the alert you can ask to the user if she want to go back anyway and, in that case, pop the controller in alertView clickedButtonAtIndex:
希望这会有所帮助.
这篇关于UINavigationBar:拦截后退按钮和后退滑动手势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!