iOS 的 UIGestureRecognizer 家族把觸控判斷抽象得很乾淨,四行程式碼就能替一個視圖加上手勢。以下用一個可縮放、可拖曳、可旋轉的 UIImageView 作為範例。
#import <UIKit/UIKit.h>
@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.userInteractionEnabled = YES; // 少了這行手勢不會觸發
// 長按
UILongPressGestureRecognizer *longPress =
[[UILongPressGestureRecognizer alloc] initWithTarget:self
action:@selector(longPress:)];
// longPress.minimumPressDuration = 0; // 設為 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 == UIGestureRecognizerStateEnded) {
_rotation = rotation.rotation + _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 == UIGestureRecognizerStateEnded) {
imgSize = _imgView.bounds.size;
}
if (imgSize.height <= 75) { // 限制最小尺寸
imgSize.height = 75;
imgSize.width = 50;
}
}
- (void)longPress:(UILongPressGestureRecognizer *)lp {
NSLog(@"長按");
}
@end
translationInView: 回傳的是「自上次重置以來的位移量」,累加完必須呼叫 setTranslation:CGPointZero,否則位移會越來越快。rotation.rotation 是相對量,必須在手勢結束時存回累加器 _rotation,下次才能接續。狀態判斷請用 UIGestureRecognizerStateEnded,而非 Cancelled。若同時啟用縮放與旋轉,建議改用 transform 統一處理(把 scale 與 rotation 組合成一個 CGAffineTransform),會比分別操作 bounds 與 transform 更不容易互相覆蓋。