欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS 滑动返回手势

程序员文章站 2024-03-24 20:20:28
...
一、首先创建BaseController,在viewDidLoad里:
id target = self.navigationController.interactivePopGestureRecognizer.delegate;

    // handleNavigationTransition:为系统私有API,即系统自带侧滑手势的回调方法,我们在自己的手势上直接用它的回调方法
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:target action:@selector(handleNavigationTransition:)];
    panGesture.delegate = self; // 设置手势代理,拦截手势触发
    [self.view addGestureRecognizer:panGesture];

    // 一定要禁止系统自带的滑动手势
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}


// 什么时候调用,每次触发手势之前都会询问下代理方法,是否触发
// 作用:拦截手势触发
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    // 当当前控制器是根控制器时,不可以侧滑返回,所以不能使其触发手势
    if(self.navigationController.childViewControllers.count == 1)
    {
        return NO;
    }

    return YES;
}

二、UIScrollView左右滑动手势与返回手势冲突的解决办法

解决办法是自定义ScrollView,重写- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event方法,代码如下:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *hitView = [super hitTest:point withEvent:event];
    if (point.x <= 10) { //这个值是调整返回手势里屏幕的距离
        hitView = nil;
    } else {
        hitView = [super hitTest:point withEvent:event];
    }
    return hitView;
}