您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS 觸摸事件的處理方式與拖曳實作

編輯:iOS 7 技巧

觸摸是行動裝置最核心的互動方式。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

四個觸摸方法的分工

  • touchesBegan:手指剛接觸螢幕時呼叫。適合記錄起始狀態、播放按下回饋。
  • touchesMoved:手指在螢幕上移動時連續呼叫。拖曳邏輯寫在這裡。
  • touchesEnded:手指離開螢幕時呼叫。適合做「位移超過閾值才算成功」的判定。
  • touchesCancelled:觸摸被系統中斷時呼叫,例如來電、通知跳出。這個方法常被忽略,但必須實作,否則你的拖曳狀態會卡在「按著」的狀態無法復原。

為什麼要用位移量而不是絕對座標

範例中刻意計算 current - previous 的差值,再疊加到原本的 center 上。若直接用手指的絕對座標設定 center,物件會「跳」到手指位置(因為按下時手指通常不在物件中心),視覺上很突兀。用位移量則能保持手指與物件的相對位置,拖曳手感才自然。

locationInView 的座標系統要注意

locationInView: 回傳的是相對於傳入那個 view 的座標系。範例傳 self.view,所以得到的座標與 image 的 frame 在同一個座標系,可以直接比較。如果誤傳了 image 本身或其他 view,計算就會出錯——這是拖曳功能最常見的 bug 來源。

現代寫法:用 UIPanGestureRecognizer

直接覆寫 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 若要接收手勢,記得把這個屬性打開——手勢辨識器的寫法則不受此限制,這也是它更方便的原因之一。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved