跳过繁文缛节直接讲解使用步骤。
1,导入代理协议(没有特殊要求可以不用添加)
.h文件:
#import <UIKit/UIKit.h>
@interface AKAddGestureView : UIViewController
@end
.m文件:
#import "AKAddGestureView"
@interface AKAddGestureView ()<UIGestureRecognizerDelegate>
2,根据需要添加属性,没全局需求可以不添加
@property (nonatomic,strong) UISwipeGestureRecognizer *left;
@property (nonatomic,strong) UISwipeGestureRecognizer *right;
@property (nonatomic,strong) UISwipeGestureRecognizer *up;
@property (nonatomic,strong) UISwipeGestureRecognizer *down;//根据需要,添加所需要手势。
@property (nonatomic,strong) UITapGestureRecognizer *tap;
@end
3,添加轻扫手势(此处以下滑手势为例,其他方向手势与此类似)
@implementation AkAddGestureView
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundcolor = [UIColor whiteColor];
}
- (void)addSwipeGestureToCurrentView{
UISwipeGestureRecognizer *down = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeGestureAction)];
self.down = down;
self.down.direction = UISwipeGestureRecognizerDirectionDown;
[self.view addGestureRecognizer:self.down];
}
- (void)swipeGestureAction{
self.view.backgroundcolor = [UIColor blueColor];
}
4.添加tap手势(点击手势中可以选择点击几次触发和几个手指有效)
- (void)addTapGestureToView{
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureAction)];
self.tap = tap;
[self.tap setNumberOfTapsRequired:2];//设置点击次数
[self.tap setNumberOfTouchesRequired:2];//设置几个手指点击有效,不设置默认为1;
[self.view addGestureRecognizer:self.tap];
}
- (void)tapGestureAction{
self.view.backgroundcolor = [UIColor lightGrayColor];
}
@end
5,有的视图中可能手势不能识别,可能该视图已经添加过手势,如有需要可以将之前禁止或者添加判断。对于tableView需要先将其滑动属性设置为NO,才能正常使用手势。
self.tableView.scrollEnabled = NO;