UIPanGestureRecognizer

平移手勢識別器檢測拖動手勢。以下示例將影象新增到檢視控制器,並允許使用者在螢幕上拖動它。

Objective-C

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageToDrag"]];
    [imageView sizeToFit];
    imageView.userInteractionEnabled = YES;
    [self.view addSubview:imageView];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [imageView 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];
}

迅速

override func viewDidLoad() {
    super.viewDidLoad()
    
    let imageView = UIImageView.init(image: UIImage.init(named: "imageToDrag"))
    imageView.sizeToFit()
    imageView.isUserInteractionEnabled = true
    self.view.addSubview(imageView)
    
    let pan = UIPanGestureRecognizer.init(target: self, action: #selector(handlePan(recognizer:)))
    imageView.addGestureRecognizer(pan)
}

func handlePan(recognizer: UIPanGestureRecognizer) {
    let translation = recognizer.translation(in: self.view)
    if let view = recognizer.view {
        view.center = CGPoint(x: view.center.x + translation.x, y: view.center.y + translation.y)
    }
    recognizer.setTranslation(CGPoint.zero, in: self.view)
}

注意: 雖然 UIPanGestureRecognizer 對於檢測任何拖動手勢很有用,但如果你只想檢測基本手勢,例如使用者向左/向右或向上/向下拖動手指,請使用 UISwipeGestureRecognizer。如果你需要訪問 translationInView:velocityInView:等方法,UIPanGestureRecognizer 是更好的選擇。