方法一:
在viewDidLoad时为UIView添加操作
响应操作绑定的事件
方法二:
在viewDidLoad时为UIView添加操作
- UISwipeGestureRecognizer
*recognizer; - recognizer
= [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)]; - [recognizer
setDirection:(UISwipeGestureRecognizer DirectionRight)]; - [[self
view] addGestureRecognizer:recognizer]; - [recognizer
release]; -
- recognizer
= [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)]; - [recognizer
setDirection:(UISwipeGestureRecognizer DirectionLeft)]; - [[self
view] addGestureRecognizer:recognizer]; - [recognizer
release]; -
- recognizer
= [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)]; - [recognizer
setDirection:(UISwipeGestureRecognizer DirectionUp)]; - [[self
view] addGestureRecognizer:recognizer]; - [recognizer
release]; -
- recognizer
= [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)]; - [recognizer
setDirection:(UISwipeGestureRecognizer DirectionDown)]; - [[self
view] addGestureRecognizer:recognizer]; - [recognizer
release];
响应操作绑定的事件
- -
(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{ -
//UISwipeGestureRecognizer DirectionLeft UISwipeGestureRecognizer DirectionRight UISwipeGestureRecognizer DirectionUp UISwipeGestureRecognizer DirectionDown -
if (recognizer.direction==UISwipeGestureRecognizer DirectionLeft ) { -
NSLog(@"Left"); -
} -
- }
方法二:
- #define
HORIZ_SWIPE_DRAG_MIN 12 - #define
VERT_SWIPE_DRAG_MAX 4 - CGPoint
startTouchPosition; - NSString
*dirString ; -
- -
(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ -
UITouch *touch = touches.anyObject; -
startTouchPosition = [touch locationInView:self.view]; - }
-
- -
(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event - {
-
UITouch *touch = touches.anyObject; -
CGPoint currentTouchPosition = [touch locationInView:self.view]; -
if (fabsf(startTouchPosition.x - currentTouchPosition.x) >= -
HORIZ_SWIPE_DRAG_MIN && -
fabsf(startTouchPosition.y - currentTouchPosition.y) <= -
VERT_SWIPE_DRAG_MAX) -
{ -
// Horizontal Swipe -
if (startTouchPosition.x < currentTouchPosition.x) { -
NSLog(@"from left"); -
dirString = @"left"; -
} -
else{ -
NSLog(@"from right"); -
dirString = @"right";} -
} -
else if (fabsf(startTouchPosition.y - currentTouchPosition.y) >= -
HORIZ_SWIPE_DRAG_MIN && -
fabsf(startTouchPosition.x - currentTouchPosition.x) <= -
VERT_SWIPE_DRAG_MAX) -
{ -
// Vertical Swipe -
if (startTouchPosition.y < currentTouchPosition.y) { -
NSLog(@"from bottom"); -
dirString = @"bottom";} -
else { -
NSLog(@"from top"); -
dirString = @"top";} -
} else -
{ -
//dirString = @""; -
} - }
-
- -
(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ -
if (dirString == @"right") { -
NSLog(@"event right"); -
}else if (dirString == @"left") { -
NSLog(@"event left"); -
} - }