ios – UISwipeGestureRecognizer只有一个方向可行

前端之家收集整理的这篇文章主要介绍了ios – UISwipeGestureRecognizer只有一个方向可行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我用pageControl创建一个页面(它是一个带有多个视图的页面,带有指示您所在页面的点),我的代码在viewDidLoad中如下所示:

UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
UIView *temp = [[UIView alloc]initWithFrame:self.view.frame];
temp.backgroundColor = [UIColor clearColor];
[temp addGestureRecognizer:swipe];
[self.view addSubview:temp];

在swipeAction选择器中我有:

- (void)swipeAction: (UISwipeGestureRecognizer *)sender{
    NSLog(@"Swipe action called");
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft) {
        //Do Something
    }
    else if (sender.direction == UISwipeGestureRecognizerDirectionRight){
        //Do Something Else
    }
}

令我惊讶的是,此方法仅在您向右滑动时起作用(即,如果调用块,则为else).向左滑动时,swipeAction甚至不会被调用!这很奇怪,为什么会发生这种情况,我该如何更改代码?任何回复表示赞赏.非常感谢!

解决方法

这里有一些你应该注意的事情.首先,您必须为要观察的每个方向创建一个手势.这不是什么大问题,因为你可以简单地给他们相同的选择器,它就像一个两个方向的手势.

UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;

UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;


UIView *temp = [[UIView alloc]initWithFrame:self.view.frame];

temp.backgroundColor = [UIColor clearColor];
[temp addGestureRecognizer:leftSwipe];
[temp addGestureRecognizer:rightSwipe];

[self.view addSubview:temp];

其次,你从未指定手势的方向,使其默认为右(或方向枚举为1)

从@L_403_0@:

The default direction is UISwipeGestureRecognizerDirectionRight. See descriptions of UISwipeGestureRecognizerDirection constants for more information.

typedef enum {
   UISwipeGestureRecognizerDirectionRight = 1 << 0,UISwipeGestureRecognizerDirectionLeft  = 1 << 1,UISwipeGestureRecognizerDirectionUp    = 1 << 2,UISwipeGestureRecognizerDirectionDown  = 1 << 3
} UISwipeGestureRecognizerDirection;

猜你在找的Xcode相关文章