UIGestureRecognizer(手勢識別器)的簡單介紹

UIGestureRecognizer就是為了識別用戶的手勢,一共六個細分的手勢,分別是:點擊(tap)、長按(longPress)、滑動(swipe)、縮放(pinch)、旋轉(rotation)、拖拽(pan)。

UIGestureRecognizer:

1.state
typedef NS_ENUM(NSInteger, UIGestureRecognizerState) {
    UIGestureRecognizerStatePossible,   
    UIGestureRecognizerStateBegan,      // 手勢開始識別
    UIGestureRecognizerStateChanged,    // 手勢改變(過程中)
    UIGestureRecognizerStateEnded,      // 手勢結束
    UIGestureRecognizerStateCancelled,  // 手勢取消
    UIGestureRecognizerStateFailed,     // 手勢失敗
    UIGestureRecognizerStateRecognized
};
2.locationInView

獲取手勢在視圖中的位置

3.delegate

為了監聽手勢的各種行為

UITapGestureRecognizer(點擊)

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(gesture:)];
tapGesture.numberOfTouchesRequired = 1;   //響應事件的手指數
tapGesture.numberOfTapsRequired = 1;     //響應事件的點擊次數
[self.view addGestureRecognizer:tapGesture];

UILongPressGestureRecognizer(長按)

UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)];
longGesture.minimumPressDuration = 1;    //響應事件的最小時間
longGesture.allowableMovement = 50;     //允許移動的距離范圍
[self.view addGestureRecognizer:longGesture];

UISwipeGestureRecognizer(滑動)

UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionRight;    //滑動的方向
swipeGesture.numberOfTouchesRequired = 1;
[self.view addGestureRecognizer:swipeGesture];

UIPinchGestureRecognizer(縮放)

UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)];
pinchGesture.scale = 2;    //縮放的比例
[self.view addGestureRecognizer:pinchGesture];

UIRotationGestureRecognizer(旋轉)

UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotation:)];
rotationGesture.rotation = M_PI_2;
[self.view addGestureRecognizer:rotationGesture];

-(void)rotationGesture:(id)sender{
     UIRotateGestureRecognizer *gesture = sender;
     if (gesture.state==UIGestureRecognizerStateChanged) {
         _imageView.transform=CGAffineTransform=Rotation(_imageView.transform,gesture.rotation);
    }
    if (gesture.state==UIGestureRecognizerStateEnded) {
      [UIView animateWithDuration:1 animations:^{
      _imageView.transform=CGAffineTransformIdentity;    //取消形變
         }];
      }
 }

UIPanGestureRecognizer(拖拽)

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)];
panGesture.minimumNumberOfTouches = 1;
panGesture.maximumNumberOfTouches = 1;
[panGesture translationInView:self.view];
[_redView addGestureRecognizer:panGesture];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容