iOS中簡單的手勢操作:長按、捏合、移動和旋轉
新建一個single view工程
ViewController.h文件
#import@interface ViewController : UIViewController { UIImageView *_imgView; float _rotation; } @end
#import "ViewController.h" @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _imgView = [[UIImageView alloc] initWithFrame:CGRectMake(110, 160, 100, 150)]; _imgView.image = [UIImage imageNamed:@"10_0.jpg"]; [self.view addSubview:_imgView]; [_imgView release]; _imgView.userInteractionEnabled = YES; //長按 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)]; // longPress.minimumPressDuration = 0;//效果等於輕觸 longPress.minimumPressDuration = 2;//最少按兩秒才會觸發事件 // [_imgView addGestureRecognizer:longPress]; [longPress release]; //捏合 UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchPress:)]; [_imgView addGestureRecognizer:pinch]; [pinch release]; //移動 UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; [_imgView addGestureRecognizer:pan]; [pan release]; //旋轉 UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotation:)]; [_imgView addGestureRecognizer:rotation]; [rotation release]; } - (void)rotation:(UIRotationGestureRecognizer *)rotation { _imgView.transform = CGAffineTransformMakeRotation(_rotation + rotation.rotation); if (rotation.state == UIGestureRecognizerStateCancelled) { _rotation = rotation.rotation+_rotation; } NSLog(@"%f", _rotation); } - (void)pan:(UIPanGestureRecognizer *)pan { CGPoint point = [pan translationInView:self.view]; _imgView.center = CGPointMake(_imgView.center.x+point.x, _imgView.center.y+point.y); [pan setTranslation:CGPointZero inView:self.view];//重置參考位置 } - (void)pinchPress:(UIPinchGestureRecognizer *)pinch { CGSize _imgSize = CGSizeMake(100, 150); float scale = pinch.scale; _imgView.bounds = CGRectMake(0, 0, _imgSize.width*scale, _imgSize.height*scale); //判斷手勢狀態 if (pinch.state == UIGestureRecognizerStateCancelled) { _imgSize = _imgView.bounds.size; } if (_imgSize.height <= 75) { _imgSize.height = 75; _imgSize.width = 50; } } - (void)longPress:(UILongPressGestureRecognizer *)lp { NSLog(@"長按"); } @end