根據滑動力度(速度)決定圖片移動速度:用力滑 → 快移,輕滑 → 慢移。
UISwipeGestureRecognizer 提供 velocity 屬性(iOS 7+),返回 CGPoint 表示水平/垂直方向速度(點/秒)。
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
swipe.direction = UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipe];
- (void)handleSwipe:(UISwipeGestureRecognizer *)gesture {
CGFloat velocity = fabs(gesture.velocity.x); // 水平速度絕對值
CGFloat duration = MAX(0.2, 1.0 - velocity / 5000.0); // 速度越快動畫越短
[UIView animateWithDuration:duration animations:^{
self.imageView.center = CGPointMake(newX, self.imageView.center.y);
}];
}
velocity 僅在手勢識別結束時有效,UIGestureRecognizerStateEnded 狀態下讀取。UIPanGestureRecognizer 的 velocityInView: 方法。