iOS手勢操作:單雙擊(點(diǎn)按)股冗、長按、捏合和蚪、拖拽止状、旋轉(zhuǎn)、橫掃

1攒霹、手勢識別器——UIGestureRecognizer 介紹
在ios開發(fā)中怯疤,除了有關(guān)觸摸的這組方法來控制使用用者的手指觸控外,還可以用UIGestureRecognizer的衍生類來進(jìn)行判斷催束。
用UIGestureRecognizer的好處在于有現(xiàn)成的手勢集峦,開發(fā)者不用自己計算手指移動軌跡,創(chuàng)建了這些手勢識別器之后可以調(diào)用視圖的addGestureRecognizer:方法,將手勢識別器注冊到某個視圖組件上塔淤。
UIGestureRecognizer是在Touch的基礎(chǔ)上封裝出來的摘昌。
UIGestureRecognizer的子類類別有以下幾種:

  • UIPanGestureRecognizer(拖動識別器)
  • UIPinchGestureRecognizer(捏合識別器)
  • UIRotationGestureRecognizer(旋轉(zhuǎn)識別器)
  • 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];
    //單擊要想執(zhí)行必須雙擊失效(如果雙擊確定偵測失敗才會觸發(fā)單擊)
    [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];
    //旋轉(zhuǎn)
    UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationAction:)];
    [self.targetView addGestureRecognizer:rotation];
    //縮放要想執(zhí)行 必須旋轉(zhuǎn)失效(如果旋轉(zhuǎn)確定偵測失敗才會觸發(fā)縮放)
    [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];//創(chuàng)建CATransition對象
    animation.delegate = self;
    animation.duration = 1.0f;//動畫持續(xù)時間
    animation.timingFunction = UIViewAnimationCurveEaseInOut;//速度控制函數(shù)高蜂,控制動畫運(yùn)行的節(jié)奏
    animation.type = kCATransitionMoveIn; //設(shè)置運(yùn)動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{
    //當(dāng)手勢按在視圖上面的點(diǎn)聪黎,轉(zhuǎn)為父系坐標(biāo) 拿到中心點(diǎn)
    /*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];*/
    //中心拖拽
    //當(dāng)你的狀態(tài)不等于結(jié)束狀態(tài),不等于失敗狀態(tài)
    /*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) {
        //計算速度向量的長度备恤,當(dāng)他小于200時稿饰,滑行會很短
        CGPoint velocity = [sender velocityInView:self.view];
        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
        CGFloat slideMult = magnitude / 200;
    
        //基于速度和速度因素計算一個終點(diǎn)
        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 ----- 旋轉(zhuǎn)
-(void)rotationAction:(UIRotationGestureRecognizer *)sender{
    sender.view.transform = CGAffineTransformRotate(sender.view.transform, sender.rotation);
    sender.rotation=10.0;//旋轉(zhuǎn)速度
}

#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:@"標(biāo)題" message:@"選擇照片" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"調(diào)用照相機(jī)");
            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(@"調(diào)用本地相冊");
            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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末湘纵,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子滤淳,更是在濱河造成了極大的恐慌梧喷,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件脖咐,死亡現(xiàn)場離奇詭異铺敌,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)屁擅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進(jìn)店門偿凭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人派歌,你說我怎么就攤上這事弯囊。” “怎么了胶果?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵匾嘱,是天一觀的道長。 經(jīng)常有香客問我早抠,道長霎烙,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任蕊连,我火速辦了婚禮悬垃,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘甘苍。我一直安慰自己尝蠕,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布载庭。 她就那樣靜靜地躺著看彼,像睡著了一般扇谣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上闲昭,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天,我揣著相機(jī)與錄音靡挥,去河邊找鬼序矩。 笑死,一個胖子當(dāng)著我的面吹牛跋破,可吹牛的內(nèi)容都是我干的簸淀。 我是一名探鬼主播,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼毒返,長吁一口氣:“原來是場噩夢啊……” “哼租幕!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起拧簸,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤劲绪,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后盆赤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體贾富,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年牺六,在試婚紗的時候發(fā)現(xiàn)自己被綠了颤枪。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,444評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡淑际,死狀恐怖畏纲,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情春缕,我是刑警寧澤盗胀,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站淡溯,受9級特大地震影響读整,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜咱娶,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一米间、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧膘侮,春花似錦屈糊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽夫晌。三九已至,卻和暖如春昧诱,著一層夾襖步出監(jiān)牢的瞬間晓淀,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工盏档, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留凶掰,地道東北人。 一個月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓蜈亩,卻偏偏與公主長得像懦窘,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子稚配,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,455評論 2 359

推薦閱讀更多精彩內(nèi)容