如果你只是想检测左右滑动,你可以把它放在你的主视图上,如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UISwipeGestureRecognizer *swipe;
swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
swipe.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipe];
swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
swipe.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipe];
}
- (void)handleSwipe:(UISwipeGestureRecognizer *)gesture
{
NSLog(@"%d", [gesture numberOfTouches]);
if (gesture.direction == UISwipeGestureRecognizerDirectionLeft)
{
NSLog(@"LEFT");
}
if (gesture.direction == UISwipeGestureRecognizerDirectionRight)
{
NSLog(@"RIGHT");
}
}
如果你想真正测试看看你是否越过了中点,你可以使用UIPanGestureRecognizer
:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]];
}
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static CGPoint startLocation;
static BOOL startAtLeft;
CGPoint location = [gesture locationInView:gesture.view];
if (gesture.state == UIGestureRecognizerStateBegan)
{
startLocation = location;
startAtLeft = (location.x < (gesture.view.frame.size.width / 2.0));
}
else if (gesture.state == UIGestureRecognizerStateEnded)
{
BOOL nowAtLeft = (location.x < (gesture.view.frame.size.width / 2.0));
if (startAtLeft != nowAtLeft)
{
if (startAtLeft)
NSLog(@"swiped across midpoint, left to right");
else
NSLog(@"swiped across midpoint, right to left");
}
}
}
使用平移手势,您可以根据自己的意愿对其进行自定义(例如,只要用户手指交叉就识别手势,而不是等待他们结束手势等)。