所以我正在制作一个带有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 if
块)。向左滑动时,swipeAction
甚至无法调用!这很奇怪,为什么会发生这种情况,我该如何更改代码?任何回复表示赞赏。非常感谢!
答案 0 :(得分:11)
这里有一些你应该注意的事情。首先,您必须为要观察的每个方向创建一个手势。这不是什么大问题,因为你可以简单地给他们相同的选择器,它就像一个两个方向的手势。
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)
默认方向是UISwipeGestureRecognizerDirectionRight。有关更多信息,请参阅UISwipeGestureRecognizerDirection常量的说明。
typedef enum {
UISwipeGestureRecognizerDirectionRight = 1 << 0,
UISwipeGestureRecognizerDirectionLeft = 1 << 1,
UISwipeGestureRecognizerDirectionUp = 1 << 2,
UISwipeGestureRecognizerDirectionDown = 1 << 3
} UISwipeGestureRecognizerDirection;
答案 1 :(得分:1)
雨燕4
let swiper = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeFunction(sender:)))
swiper.direction = UISwipeGestureRecognizer.Direction.right
let swipel = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeFunction(sender:)))
swipel.direction = UISwipeGestureRecognizer.Direction.left
UIView().addGestureRecognizer(swiper)
UIView().addGestureRecognizer(swipel)
@objc func swipeFunction(sender: UISwipeGestureRecognizer) {
print(sender)
}
您应该能够从那里弄清楚,您可以为每个方向的UIView添加一个UISwipeGestureRecognizer
答案 2 :(得分:0)
swipe.direction设置您正在识别的方向,它不会告诉您哪个方向被刷过。在创建识别器时添加此行:
swipe.direction = UISwipeGestureRecognizerDirectionLeft|UISwipeGestureRecognizerDirectionRight;
如果您需要检测哪个方向被滑动,只需使用两个不同的识别器,一个用于左侧,一个用于右侧。