iOS 手势
Posted yzVictory
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 手势相关的知识,希望对你有一定的参考价值。
手势识别在ios上非常重要,手势操作移动设备的重要特征,极大的增加了移动设备使用便捷性。iOS 中手势包括:UITapGestureRecognizer(点击),UIPinchGestureRecognizer(捏合),UIRotationGestureRecognizer(旋转),UISwipeGestureRecognizer(轻扫),UIPanGestureRecognizer(移动),UILongPressGestureRecognizer(长按)。上面的类属性和方法都比较简单,有几个方法个人感觉不容易理解的,在这里说明一下。
- (void)viewDidLoad { [super viewDidLoad]; image1 = [[UIImageView alloc]initWithFrame:CGRectMake(80, 20, 200, 200)]; image1.image = [UIImage imageNamed:@"0.jpg"]; image1.userInteractionEnabled = YES; [self.view addSubview:image1]; //点击 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)]; [image1 addGestureRecognizer:tap]; //捏合 UIPinchGestureRecognizer *pin = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pin:)]; [image1 addGestureRecognizer:pin]; //旋转 UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotation:)]; [image1 addGestureRecognizer:rotation]; //轻扫 UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipe:)]; [image1 addGestureRecognizer:swipe]; //移动 UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)]; [image1 addGestureRecognizer:pan]; // Do any additional setup after loading the view, typically from a nib. } -(void) tap:(UITapGestureRecognizer *)gestureRecognizer { CGPoint point1 = [gestureRecognizer locationInView:image1]; NSLog(@"point1 = %@",NSStringFromCGPoint(point1)); } - (void)pin:(UIPinchGestureRecognizer *)gestureRecognizer { NSLog(@"scale = %f;velocity = %f",gestureRecognizer.scale,gestureRecognizer.velocity); image1.transform = CGAffineTransformMakeScale(gestureRecognizer.scale, gestureRecognizer.scale); } - (void)rotation:(UIRotationGestureRecognizer *)gestureRecognizer { image1.transform = CGAffineTransformMakeRotation(gestureRecognizer.rotation); } - (void)swipe:(UISwipeGestureRecognizer *)gestureRecognizer { image1.image = [UIImage imageNamed:@"2.jpg"]; } - (void)pan:(UIPanGestureRecognizer *)gestureRecognizer { //相对于手指开始的位置 CGPoint point1 = [gestureRecognizer translationInView:image1]; //相对于View左上角的位置 CGPoint point2 = [gestureRecognizer locationInView:image1]; CGFloat centerX = image1.center.x; CGFloat centerY = image1.center.y; image1.center = CGPointMake(centerX + point1.x, centerY + point1.y); //注意这里 [gestureRecognizer setTranslation:CGPointMake(0, 0) inView:image1]; NSLog(@"point1 = %@ ; point2 = %@",NSStringFromCGPoint(point1),NSStringFromCGPoint(point2)); }
手势的使用很简单,demo就不上传了。
自定义手势
自定义手势继承:UIGestureRecognizer,实现下面的方法:
– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:
- touchesCancelled:withEvent:
手势冲突处理
- (void)requireGestureRecognizerToFail:(UIGestureRecognizer *)otherGestureRecognizer;
如果otherGestureRecognizer执行失败,则执行调用者的手势。
以上是关于iOS 手势的主要内容,如果未能解决你的问题,请参考以下文章