iOS手勢操作:單雙擊(點按)、長按、捏合、拖拽、旋轉、橫掃

1、手勢識別器——UIGestureRecognizer 介紹
在ios開發中,除了有關觸摸的這組方法來控制使用用者的手指觸控外,還可以用UIGestureRecognizer的衍生類來進行判斷。
用UIGestureRecognizer的好處在于有現成的手勢,開發者不用自己計算手指移動軌跡,創建了這些手勢識別器之后可以調用視圖的addGestureRecognizer:方法,將手勢識別器注冊到某個視圖組件上。
UIGestureRecognizer是在Touch的基礎上封裝出來的。
UIGestureRecognizer的子類類別有以下幾種:

  • UIPanGestureRecognizer(拖動識別器)
  • UIPinchGestureRecognizer(捏合識別器)
  • UIRotationGestureRecognizer(旋轉識別器)
  • UITapGestureRecognizer(輕拍識別器)
  • UILongPressGestureRecognizer(長按識別器)
  • UISwipeGestureRecognizer(掃動識別器)

2、各個手勢的例子:

#import "ViewController.h"

@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIView *targetView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //單擊
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction:)];
    [self.view addGestureRecognizer:singleTap];
    //雙擊
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapAction:)];
    doubleTap.numberOfTapsRequired = 2;
    [self.view addGestureRecognizer:doubleTap];
    //單擊要想執行必須雙擊失效(如果雙擊確定偵測失敗才會觸發單擊)
    [singleTap requireGestureRecognizerToFail:doubleTap];
    //長按手勢
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    [self.targetView addGestureRecognizer:longPress];
    //捏合手勢
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGestureAction:)];
    [self.targetView addGestureRecognizer:pinchGesture];
    //拖拽
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    [self.targetView addGestureRecognizer:panGesture];
    //旋轉
    UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationAction:)];
    [self.targetView addGestureRecognizer:rotation];
    //縮放要想執行 必須旋轉失效(如果旋轉確定偵測失敗才會觸發縮放)
    [pinchGesture requireGestureRecognizerToFail:rotation];
    //左橫掃
    UISwipeGestureRecognizer *leftSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipAction:)];
    [self.view addGestureRecognizer:leftSwipeGesture];    
    leftSwipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    //右橫掃
    UISwipeGestureRecognizer *rightSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipAction:)];
    [self.view addGestureRecognizer:rightSwipeGesture];    
    rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
    //下橫掃
    UISwipeGestureRecognizer *downSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipAction:)];
    [self.view addGestureRecognizer:downSwipeGesture];    
    downSwipeGesture.direction = UISwipeGestureRecognizerDirectionDown;
    //上橫掃
    UISwipeGestureRecognizer *upSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipAction:)];
    [self.view addGestureRecognizer:upSwipeGesture];
    upSwipeGesture.direction = UISwipeGestureRecognizerDirectionUp;

}
#pragma mark -----橫掃
-(void)swipAction:(UISwipeGestureRecognizer *)sender{
    CATransition *animation = [CATransition animation];//創建CATransition對象
    animation.delegate = self;
    animation.duration = 1.0f;//動畫持續時間
    animation.timingFunction = UIViewAnimationCurveEaseInOut;//速度控制函數,控制動畫運行的節奏
    animation.type = kCATransitionMoveIn; //設置運動type
    switch (sender.direction) {
        case UISwipeGestureRecognizerDirectionRight: //向右滑
        {
            animation.subtype = kCATransitionFromLeft;//視圖從左開始
        }
            break;
        case UISwipeGestureRecognizerDirectionLeft:
        {
            animation.subtype = kCATransitionFromRight;//視圖向左滑
        }
            break;
        case UISwipeGestureRecognizerDirectionUp://向上滑
        {
            animation.subtype = kCATransitionFromTop;
        }
            break;
        case UISwipeGestureRecognizerDirectionDown: //向下滑
        {
            animation.subtype = kCATransitionFromBottom;
        
        }
            break;
        default:
            break;
    }
    [sender.view.layer addAnimation:animation forKey:@"move in"];
}
#pragma mark ------ 拖拽
-(void)panAction:(UIPanGestureRecognizer *)sender{
    //當手勢按在視圖上面的點,轉為父系坐標 拿到中心點
    /*CGPoint translatedPoint=[sender translationInView:self.view];
    CGFloat firstX;
    CGFloat firstY;
     if ([sender state]==UIGestureRecognizerStateBegan) {
         firstX=[sender.view center].x;
         firstY=[sender.view center].y;
     
     }
     translatedPoint=CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
     [sender.view setCenter:translatedPoint];*/
    //中心拖拽
    //當你的狀態不等于結束狀態,不等于失敗狀態
    /*if (sender.state != UIGestureRecognizerStateEnded && sender.state != UIGestureRecognizerStateFailed) {
        CGPoint location = [sender locationInView:sender.view.superview];
        sender.view.center = location;
    }*/

    //視圖前置操作
    [sender.view.superview bringSubviewToFront:sender.view];
    //拖拽
    CGPoint center = sender.view.center;
    CGFloat cornerRadius = sender.view.frame.size.width / 2;
    CGPoint translation = [sender translationInView:self.view];
     //NSLog(@"%@", NSStringFromCGPoint(translation));
    sender.view.center = CGPointMake(center.x + translation.x,center.y +translation.y);
    [sender setTranslation:CGPointZero inView:self.view];
    //動畫效果
    if (sender.state == UIGestureRecognizerStateEnded) {
        //計算速度向量的長度,當他小于200時,滑行會很短
        CGPoint velocity = [sender velocityInView:self.view];
        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
        CGFloat slideMult = magnitude / 200;
    
        //基于速度和速度因素計算一個終點
        float slideFactor = 0.1 * slideMult;
        CGPoint finalPoint = CGPointMake(center.x + (velocity.x * slideFactor),center.y + (velocity.y * slideFactor));
        //限制最小[cornerRadius]和最大邊界值[    self.view.bounds.size.width - cornerRadius],以免拖動出屏幕界限
        finalPoint.x = MIN(MAX(finalPoint.x, cornerRadius),self.view.bounds.size.width - cornerRadius);
        finalPoint.y = MIN(MAX(finalPoint.y, cornerRadius),self.view.bounds.size.height - cornerRadius);
        [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut
     animations:^{
             sender.view.center = finalPoint;
        }
         completion:nil];

    }

}
#pragma mark ----- 旋轉
-(void)rotationAction:(UIRotationGestureRecognizer *)sender{
    sender.view.transform = CGAffineTransformRotate(sender.view.transform, sender.rotation);
    sender.rotation=10.0;//旋轉速度
}

#pragma mark ----- 縮放
-(void)pinchGestureAction:(UIPinchGestureRecognizer *)sender{
    NSLog(@"xxx");
    sender.view.transform=CGAffineTransformMakeScale(sender.scale, sender.scale);
}
# pragma mark -----長按
-(void)longPressAction:(UILongPressGestureRecognizer *)sender{
    if (sender.state == UIGestureRecognizerStateEnded) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"標題" message:@"選擇照片" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"調用照相機");
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *imagepicker = [[UIImagePickerController alloc] init];
                imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                imagepicker.delegate = self;
                imagepicker.allowsEditing = YES;//允許圖片被編輯
                imagepicker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
                [self presentViewController:imagepicker animated:NO completion:nil];
            
            }
        }];
        [alertController addAction:photoAction];
        UIAlertAction *libraryAction=[UIAlertAction actionWithTitle:@"相冊" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"調用本地相冊");
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                UIImagePickerController *picker =
                [[UIImagePickerController alloc] init];
                picker.delegate=self;
                picker.allowsEditing = YES;
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
               [self presentViewController:picker animated:NO completion:nil];
            
            }
         }];
        [alertController addAction:libraryAction];
        UIAlertAction *cancleAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"取消");
            }];
        [alertController addAction:cancleAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
#pragma mark ---- 單擊
-(void)singleTapAction:(UITapGestureRecognizer *)sender{
    NSLog(@"單擊");
    //改變背景顏色
    if (sender.view.backgroundColor==[UIColor whiteColor]) {
        sender.view.backgroundColor=[UIColor cyanColor];
    }else{
        sender.view.backgroundColor=[UIColor whiteColor];
    }
}  
#pragma mark------- 雙擊
-(void)doubleTapAction:(UITapGestureRecognizer *)sender{
    NSLog(@"雙擊");
}

@end
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容