首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

iOS 拖曳手勢實作圖片移動效果完整教學

     編輯:關於C++

使用 UIPanGestureRecognizer 實現圖片跟隨手指拖曳移動的經典 iOS 交互效果,關鍵在於正確處理座標系轉換與位移重置。

完整實作步驟

1. 建立手勢識別器與圖片視圖

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] 
    initWithTarget:self action:@selector(pan:)];

UIImage *image = [UIImage imageNamed:@"your_image.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 40, 80, 80)];
imageView.image = image;
imageView.userInteractionEnabled = YES;  // 關鍵:啟用用戶交互

[self.view addSubview:imageView];
[imageView addGestureRecognizer:pan];

2. 實作拖曳處理方法

- (void)pan:(UIPanGestureRecognizer *)gesture {
    // 獲取在父視圖座標系中的位移量
    CGPoint translation = [gesture translationInView:self.view];
    
    // 更新視圖中心點:當前中心 + 位移增量
    gesture.view.center = CGPointMake(
        gesture.view.center.x + translation.x,
        gesture.view.center.y + translation.y
    );
    
    // 關鍵:重置位移量為零,避免累積誤差
    [gesture setTranslation:CGPointZero inView:self.view];
}

核心原理解析

關鍵點說明
userInteractionEnabled = YESUIImageView 預設關閉交互,必須啟用才能接收手勢事件
translationInView:返回手勢識別器視圖在指定視圖座標系中的位移向量
中心點更新直接修改 center 屬性比修改 frame 更高效、無需重新計算尺寸
setTranslation:CGPointZero將位移歸零,確保下次回調獲得的是增量而非累積值

常見坑點與解決方案

  • 圖片不跟隨移動:檢查 userInteractionEnabled 是否設為 YES
  • 移動抖動/跳躍:確認 setTranslation:CGPointZero 在正確視圖座標系中調用
  • 超出螢幕邊界:可在更新中心點前加入邊界檢查邏輯
  • 多手勢衝突:實作 gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: 協調手勢優先級

進階擴展

// 添加彈性動畫效果
- (void)pan:(UIPanGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateEnded) {
        [UIView animateWithDuration:0.3 
                         delay:0 
         usingSpringWithDamping:0.5 
          initialSpringVelocity:0 
                        options:0 
                     animations:^{
            // 吸附到邊緣或特定位置
            gesture.view.center = targetCenter;
        } completion:nil];
    }
    // ... 其餘邏輯
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved