觸摸是行動裝置最核心的互動方式。iOS 把觸摸包裝成 UITouch 物件,透過四個方法回報生命週期中的各個階段。以下用一個可拖曳的 UIImageView 示範。
@implementation TouchEvenViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *_image = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 150, 169)];
[_image setImage:[UIImage imageNamed:@"zmit"]];
[self.view addSubview:_image];
}
#pragma mark - 視圖控制器的觸摸事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"開始觸摸");
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
// 取得一個觸摸物件(多點觸時會有多個)
UITouch *touch = [touches anyObject];
// 目前位置
CGPoint current = [touch locationInView:self.view];
// 上一個位置
CGPoint previous = [touch previousLocationInView:self.view];
// 移動前的中心點
CGPoint center = _image.center;
// 計算位移量
CGPoint offset = CGPointMake(current.x - previous.x, current.y - previous.y);
// 套用新位置
_image.center = CGPointMake(center.x + offset.x, center.y + offset.y);
NSLog(@"觸摸中");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"觸摸結束");
}
@end
範例中刻意計算 current - previous 的差值,再疊加到原本的 center 上。若直接用手指的絕對座標設定 center,物件會「跳」到手指位置(因為按下時手指通常不在物件中心),視覺上很突兀。用位移量則能保持手指與物件的相對位置,拖曳手感才自然。
locationInView: 回傳的是相對於傳入那個 view 的座標系。範例傳 self.view,所以得到的座標與 image 的 frame 在同一個座標系,可以直接比較。如果誤傳了 image 本身或其他 view,計算就會出錯——這是拖曳功能最常見的 bug 來源。
直接覆寫 touches 系列方法能用,但實務上更推薦手勢辨識器,因為它自動處理了多點觸、取消狀態與系統衝突:
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self
action:@selector(handlePan:)];
[_image addGestureRecognizer:pan];
[self.view addGestureRecognizer:pan];
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointZero inView:self.view];
}
這裡有個關鍵細節:取出 translation 後必須呼叫 setTranslation:CGPointZero 歸零,否則每次回呼回傳的都是「從手勢開始到現在的總位移」,物件會加速飛出畫面。
另外,覆寫 touches 方法只在 view 的 userInteractionEnabled 為 YES 時才會收到事件。UIImageView 與 UILabel 預設是 NO,所以範例中的 image 若要接收手勢,記得把這個屬性打開——手勢辨識器的寫法則不受此限制,這也是它更方便的原因之一。