您的位置:首页 > 移动开发 > IOS开发

iOS 自定义手势

2016-05-03 14:14 381 查看
下面是实践过后总结的具体步骤,例子代码实现了一个一横一竖画一个十字的手势:

首先创建UIGestureRecognizer的子类。

#import <UIKit/UIKit.h>

@interface CustomTouch2: UIGestureRecognizer

@end

在.m文件import UIGestureRecognizerSubclass.h
#import <UIKit/UIGestureRecognizerSubclass.h>

在.m中实现

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

其中,
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
中可能需要实现记录手势的起始位置的操作

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
中可能要实现一些检查,当手势动作达到设定位置时触发手势回调方法,在这里需要设置state为UIGestureRecognizerStateEnded
if (self.state == UIGestureRecognizerStatePossible) {
[self setState:UIGestureRecognizerStateEnded];
}

另外,viewController中要对对应的View添加 addGestureRecognizer

- (void)viewDidLoad {
[super
viewDidLoad];
CustomTouch2 *customTouch = [[CustomTouch2
alloc] initWithTarget:self
action:@selector(handleTouch:)];
[self.view
addGestureRecognizer:customTouch];
}

- (void) handleTouch:(UIRotationGestureRecognizer*) recognizer
{
NSLog(@"你触发的手势");
}

下面是我实现的一个十字手势的代码:
#import "CustomTouch2.h"
#import <UIKit/UIGestureRecognizerSubclass.h>
@interface CustomTouch2()
{
CGPoint curTickleStart;
BOOL arriveFirstPoint;
BOOL arriveLastPoint;
}
@end

static int touchTimes = 0;

@implementation CustomTouch2
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
curTickleStart = [touch locationInView:self.view];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

UITouch * touch = [touches anyObject];
CGPoint ticklePoint = [touch locationInView:self.view];
CGFloat horizontal = ticklePoint.x - curTickleStart.x;
CGFloat vertical = ticklePoint.y - curTickleStart.y;

if (!arriveFirstPoint && vertical >= 50 && (horizontal <= 10 || horizontal >= -10)) {
arriveFirstPoint = YES;
touchTimes ++;
}

if (arriveFirstPoint && (vertical <= 10 || vertical >= -10) && horizontal >= 50){
arriveLastPoint = YES;
touchTimes ++;
}

if (touchTimes == 2 && self.state == UIGestureRecognizerStatePossible ) {
[self setState:UIGestureRecognizerStateEnded];
touchTimes = 0;
arriveFirstPoint = NO;

}
}
- (void)reset {
curTickleStart = CGPointZero;
if (self.state == UIGestureRecognizerStatePossible) {
[self setState:UIGestureRecognizerStateFailed];
}
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self reset];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self reset];
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: