在创建的UIView子类或者UIViewController的 init方法,或者 loadView或者 viewDidLoad等方法中加入手势识别器。
并用选择器指定响应动作对象方法。
一下是UIVew中加入方式
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
//向右滑动
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
[self addGestureRecognizer:swipeRight];
//向左滑动
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self addGestureRecognizer:swipeLeft];
//单击事件
UITapGestureRecognizer* singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SingleTap:)];
//点击的次数
singleRecognizer.numberOfTapsRequired = 1;
//给self.view添加一个手势监测;
[self addGestureRecognizer:singleRecognizer];
//双击事件
UITapGestureRecognizer* doubleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(DoubleTap:)];
doubleTapRecognizer.numberOfTapsRequired = 2;
//关键语句,给self.view添加一个手势监测;
[self addGestureRecognizer:doubleRecognizer];
//button长按事件
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
longPress.minimumPressDuration = 0.4; //定义按的时间
[self addGestureRecognizer:longPress];
}
return self;
}
#pragma mark - 左右移动手势响应动作处理方法
-(void)swipe:(UISwipeGestureRecognizer *)g
{
if ( g.direction == UISwipeGestureRecognizerDirectionRight )
{
NSLog(@"right->");
} else {
NSLog(@"<-left");
}
}
#pragma mark - 处理单击操作
-(void) SingleTap:(UITapGestureRecognizer*) g
{
NSLog(@"Tap");
}
#pragma mark - 处理双击操作
-(void) DoubleTap:(UITapGestureRecognizer*) g
{
NSLog(@"Tap");
}
#pragma mark - 按钮长按处理方法
-(void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer
{
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan)
{
}
}
如果在UIViewController中使用,指定好哪个UIView控件使用即可,例如
给webview加入向左滑动
[webview addGestureRecognizer:swipeLeft];
给搜索按钮加入长按事件
[searchButton addGestureRecognizer:longPress];
UIGestureRecognizer基类是一个抽象类,主要是使用它的以下子类来实现各种手势
长按
UILongPressGestureRecognizer
拖动
UIPanGestureRecognizer
捏合
UIPinchGestureRecognizer
旋转
UIRotationGestureRecognizer
滑动
UISwipeGestureRecognizer
点击
UITapGestureRecognizer
参考IOS官方文档: UIGestureRecognizer