在 iOS 中,UIView 繼承自 UIResponder,因此可回應觸控事件。若要讓 view 可拖動,最常使用 touchesBegan:withEvent: 與 touchesMoved:withEvent:。
基本思路是:在 touchesBegan 記錄起始點,在 touchesMoved 計算位移,並更新 view 的 frame 或 center。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
self.beginPoint = [touch locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint current = [touch locationInView:self];
CGRect frame = self.frame;
frame.origin.x += current.x - self.beginPoint.x;
frame.origin.y += current.y - self.beginPoint.y;
self.frame = frame;
}
若要避免 view 被拖出畫面,可在更新 center 後檢查父視圖邊界,並將 x、y 限制在可視範圍內。若希望拖曳結束後自動吸附到某個位置,則可再實作 touchesEnded:withEvent:。