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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,963評論 6 542
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,348評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,083評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,706評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,442評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,802評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,795評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,983評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,542評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,287評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,486評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,030評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,710評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,116評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,412評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,224評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,462評論 2 378

推薦閱讀更多精彩內容