首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 滑動手勢速度感知:UISwipeGestureRecognizer velocity 屬性

     編輯:程式設計綜合問答

需求

根據滑動力度(速度)決定圖片移動速度:用力滑 → 快移,輕滑 → 慢移。

解決方案

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: 方法。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved