本文实例为大家分享了iOS手势的具体实现代码,供大家参考,具体内容如下
效果

细节
1.UITouch
#import "ViewController_0.h"
@interface ViewController_0 ()
@property (nonatomic, strong)UILabel *label;
@end
@implementation ViewController_0
- (void)viewDidLoad {
[super viewDidLoad];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
self.label.backgroundColor = [UIColor yellowColor];
self.label.layer.borderWidth = 1;
[self.view addSubview:self.label];
UILabel *textlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 200, 45)];
textlabel.text = @"拖动方块";
[textlabel sizeToFit];
textlabel.font = [UIFont systemFontOfSize:12];
[self.view addSubview:textlabel];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
//1.拿到手势
UITouch *touch = [touches anyObject];
//2.拿到touch 所在view的坐标
CGPoint point = [touch locationInView:self.view];
//3.让label拿到坐标
self.label.center = point;
NSLog(@"1.手指接触到了屏幕");
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
//1.拿到手势
UITouch *touch = [touches anyObject];
//2.拿到touch 所在view的坐标
CGPoint point = [touch locationInView:self.view];
//3.让label拿到坐标
self.label.center = point;
NSLog(@"2.手指在屏幕上移动");
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
NSLog(@"3.手指刚离开屏幕");
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
NSLog(@"4.手势失效了");
}
@end
2.UITapGestureRecognizer
#import "ViewController_1.h"
@interface ViewController_1 ()
@property (nonatomic, strong) UILabel *label;
@end
@implementation ViewController_1
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *textlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 200, 45)];
textlabel.text = @"电脑上操作tap手势 alt +shift 需要连续点击次数2次";
[textlabel sizeToFit];
textlabel.font = [UIFont systemFontOfSize:12];
[self.view addSubview:textlabel];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(100, 150, 100, 100)];
self.label.backgroundColor = [UIColor orangeColor];
self.label.userInteractionEnabled = YES;
self.label.text = @"0";
self.label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:self.label];
// 1.创建tap手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap:)];
tap.numberOfTapsRequired = 2; //需要轻轻点击的次数
tap.numberOfTouchesRequired = 2;//需要的手指数量 :2根手指alt +shift 需要匹配点击次数2次(其实直接用默认的就好)
[self.label addGestureRecognizer:tap];
}
- (void)labelTap:(UITapGestureRecognizer *)tap {
int num = [self.label.text intValue];
num++;
self.label.text = [NSString stringWithFormat:@"%d",num ];
}
@end










