简体   繁体   English

UINavigationBar:拦截后退按钮和后退滑动手势

[英]UINavigationBar: intercept back button and back swipe gesture

I have a UINavigationBar that intercepts the back button tap that alerts the user if there are unsave changes. 我有一个UINavigationBar拦截后退按钮点击,如果有未保存的更改,它会提醒用户。 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; 这基于UINavigationController和UINavigationBarDelegate.ShouldPopItem()中提供的解决方案使用UINavigationBarDelegate协议和实现- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;

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:)]; 现在,iOS7已经引入了向后移动的手势,我也想拦截它,但是无法使用我迄今为止发现的解决方案,即使用[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? 有小费吗?

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: 要拦截后滑动手势,您可以将self设置为手势的委托( <UIGestureRecognizerDelegate> ),然后根据未保存的更改从gestureRecognizerShouldBegin返回YES或NO:

// 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;
}

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: 在警报中,您可以询问用户是否还要返回,在这种情况下,在alertView clickedButtonAtIndex:弹出控制器alertView clickedButtonAtIndex:

Hope this is of some help. 希望这个对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM