iOS-個(gè)人整理07 - touch觸摸事件和手勢識(shí)別器

一、touch觸摸事件

在給定的觸摸階段,如果發(fā)生觸摸事件,應(yīng)用程序就會(huì)發(fā)送下列消息
//觸屏開始-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//觸屏結(jié)束,手指離開屏幕-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
//滑動(dòng)-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
//觸屏取消,觸摸被打斷,來電話,短信等-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

下面的TouchView實(shí)現(xiàn)了創(chuàng)建一塊View,點(diǎn)擊變成紅色,觸摸離開變成黑色,按住拖拽會(huì)變成隨機(jī)色,同時(shí)View的圖塊也會(huì)隨著拖拽而移動(dòng)

#import "TouchView.h"  
  
@implementation TouchView  
  
//每一個(gè)UIView或者其子類,都可以實(shí)現(xiàn)觸摸事件,重寫系統(tǒng)提供的方法  
  
//觸摸開始,觸摸對(duì)象觸摸屏幕  
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  
{  
    NSLog(@"%s,開始",__func__);  
    self.backgroundColor = [UIColor redColor];  
}  
  
//觸摸對(duì)象在屏幕上移動(dòng)  
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event  
{  
    NSLog(@"%s,移動(dòng)",__func__);  
    self.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];  
      
    //得到某個(gè)觸摸對(duì)象,如果支持多點(diǎn)觸摸,可得到多個(gè)對(duì)象  
    UITouch *touch = touches.anyObject;  
    //得到觸摸對(duì)象當(dāng)前點(diǎn)  
    CGPoint locationPoint = [touch locationInView:self.superview];  
    //得到移動(dòng)之前所在的點(diǎn)  
    CGPoint prePoint = [touch previousLocationInView:self.superview];  
    //計(jì)算delX delY,就是x,y所移動(dòng)的距離  
      
    float delX = locationPoint.x - prePoint.x;  
    float delY = locationPoint.y - prePoint.y;  
      
    CGRect frame = self.frame;  
      
    //獲取整個(gè)屏幕寬度  
    float screenWidth = [UIScreen mainScreen].bounds.size.width;  
    float screenHeight = [UIScreen mainScreen].bounds.size.height;  
      
    float x = frame.origin.x;  
    float y = frame.origin.y;  
  
    //讓視圖無法拖出屏幕的范圍  
    if (x + delX < 0 || y + delY < 0 || x + frame.size.width + delX > screenWidth || y +frame.size.height + delY > screenHeight) {  
        NSLog(@"超出");  
    }  
    else  
    {  
        self.center = CGPointMake(self.center.x + delX, self.center.y + delY);  
    }  
    //移動(dòng)中改變視圖大小  
    //self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width + delX, self.frame.size.height + delY);  
}  
  
//手指離開屏幕  
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event  
{  
    NSLog(@"%s,結(jié)束",__func__);  
    self.backgroundColor = [UIColor blackColor];  
}  
  
//觸摸被打斷,來電話,短信等  
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event  
{  
    NSLog(@"%s,打斷",__func__);  
}  
@end  

二、手勢識(shí)別器

手勢識(shí)別器是對(duì)觸摸事件進(jìn)行了封裝,本身起到了識(shí)別作用
傳說中IOS有七種手勢
輕拍 UITapGestureRecognizer
輕掃 UISwipeGestureRecognizer
沿屏幕邊緣輕掃 UIScreenEdgePanGestureRecognizer
捏合 UIPinchGestureRecognizer
旋轉(zhuǎn) UIRotationGestureRecognizer
平移 UIPanGestureRecognizer
長按 UILongPressGestureRecognizer

下面先使用了輕拍,輕掃和沿屏幕邊緣輕掃。
基本過程
1.先初始化手勢

UITapGestureRecognizer *tagGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];  
[headImageView addGestureRecognizer:tagGesture];  

2.設(shè)置手勢屬性

//需要的觸摸次數(shù)  
   tagGesture.numberOfTapsRequired = 1;  
   //需要的觸摸對(duì)象的個(gè)數(shù)  
   tagGesture.numberOfTouchesRequired = 2;  

3.給View添加手勢

[self.view addGestureRecognizer:tagGesture];  

4.實(shí)現(xiàn)手勢方法

-(void)tapAction:(UITapGestureRecognizer *)sender  
{  
    NSLog(@"輕拍");  
}  

#import "RootViewController.h"  
#import "TapView.h"  
  
@interface RootViewController ()<UIGestureRecognizerDelegate>  
  
@end  
@implementation RootViewController  
  
  
-(void)viewDidLoad  
{  
    [super viewDidLoad];       
  
     //1.創(chuàng)建輕拍手勢    
    UITapGestureRecognizer *tagGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];  
    [headImageView addGestureRecognizer:tagGesture];  
    //需要的觸摸次數(shù)  
    tagGesture.numberOfTapsRequired = 1;  
    //需要的觸摸對(duì)象的個(gè)數(shù)  
    tagGesture.numberOfTouchesRequired = 2;  
    [self.view addGestureRecognizer:tagGesture];  
  
    //2.創(chuàng)建輕掃手勢  
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)]; 
    //掃動(dòng)方向 
    swipeGesture.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft; [self.view addGestureRecognizer:swipeGesture]; 
    //3.創(chuàng)建屏幕邊緣輕掃手勢 
UIScreenEdgePanGestureRecognizer *pan = [[UIScreenEdgePanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)]; [self.view addGestureRecognizer:pan];  
    //邊緣設(shè)置  
    pan.edges = UIRectEdgeLeft; 
    //指定手勢代理 
    swipeGesture.delegate = self;}  
#pragma mark 手勢代理
//如果視圖添加了多個(gè)手勢,此代理方法如果返回值為YES:運(yùn)行識(shí)別多個(gè)手勢勢 
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:  
          (UIGestureRecognizer *)otherGestureRecognizer{ return YES;}  
  
 //手勢開關(guān)  
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer  
{   
    //判斷一個(gè)視圖的類型,如果是button類型,就不響應(yīng)手勢,這樣點(diǎn)擊button和手勢就不會(huì)同時(shí)觸發(fā)   
    if ([[gestureRecognizer view] isKindOfClass:[UIButton class]])   
    {  
         return NO;   
    }   
    return YES;  
}  
  
//輕拍手勢觸發(fā)的方法  
-(void)tapAction:(UITapGestureRecognizer *)sender  
{  
    //得到輕拍的點(diǎn)  
    //獲取點(diǎn)  
    CGPoint point=[sender locationInView:sender.view];  
    NSLog(@"輕拍");  
}  
  

下面代碼實(shí)現(xiàn)了捏合,選擇,長按,平移手勢
這里還涉及了View的圖像變化
UIview有一個(gè)transform屬性,可以對(duì)View進(jìn)行旋轉(zhuǎn),縮放平移等操作,按住option鍵可以實(shí)現(xiàn)在模擬器上進(jìn)行兩指操作

#import "SecondViewController.h"  
//需要遵守代理協(xié)議  
@interface SecondViewController ()<UIGestureRecognizerDelegate>  
  
@end  
  
@implementation SecondViewController  
  
-(void)viewDidLoad  
{  
    [super viewDidLoad];  
      
    //初始化一個(gè)UIImageView  
    UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];  
    [myImageView setImage:[UIImage imageNamed:@"background.jpg"]];  
    myImageView.center = self.view.center;  
    [self.view addSubview:myImageView];  
    myImageView.userInteractionEnabled = YES;  
      
#pragma mark 手勢2  
      
    //旋轉(zhuǎn)手勢  
    UIGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotationAction:)];  
    //添加手勢  
    [myImageView addGestureRecognizer:rotation];  
    //設(shè)置代理  
    rotation.delegate = self;  
      
    //捏合手勢  
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchAction:)];  
    [myImageView addGestureRecognizer:pinch];  
    //設(shè)置代理  
    pinch.delegate = self;  
      
    //平移手勢  
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];  
    [myImageView addGestureRecognizer:pan];  
      
    //長按手勢  
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];  
    //長按時(shí)間,默認(rèn)0.5  
    longPress.minimumPressDuration = 1;  
    //長按時(shí)可移動(dòng)范圍  
    longPress.allowableMovement = 100;  
    [myImageView addGestureRecognizer:longPress];  
    //添加代理  
    longPress.delegate = self;  
      
}  
  
//長按方法  
-(void)longPressAction:(UILongPressGestureRecognizer*)sender  
{  
    //進(jìn)行判斷,長按開始的時(shí)候,不設(shè)置則長按離開也會(huì)觸發(fā)  
    if (sender.state == UIGestureRecognizerStateBegan) {  
       NSLog(@"長按");  
    }  
    else if (sender.state == UIGestureRecognizerStateEnded)  
    {  
        NSLog(@"長按結(jié)束");  
    }  
    else if (sender.state == UIGestureRecognizerStateChanged)  
    {  
        NSLog(@"長按變化");  
    }  
    
}  
  
#pragma mark 實(shí)現(xiàn)手勢方法  
//平移方法  
-(void)panAction:(UIPanGestureRecognizer*)sender  
{  
    UIView *myView = [sender view];  
    //得到偏移量  
    CGPoint translation = [sender translationInView:myView];  
    //通過2D仿射函數(shù)中與位移相關(guān)的函數(shù)來改變視圖位置  
    //tx,ty X,Y方向的位移  
    myView.transform = CGAffineTransformTranslate(myView.transform, translation.x, translation.y);  
    //設(shè)置偏移歸位CGPointZero = CGPointMake(0,0)  
    [sender setTranslation:CGPointZero inView:myView];  
      
}  
  
//捏合方法  
-(void)pinchAction:(UIPinchGestureRecognizer*)sender  
{  
    UIView *myView = [sender view];  
    //縮放大小  
    float myScale = sender.scale;  
    //通過2D仿射變換函數(shù)與縮放有關(guān)的函數(shù)改變視圖大小  
    myView.transform = CGAffineTransformScale(myView.transform, myScale, myScale);  
    //復(fù)原  
    sender.scale = 1;  
}  
  
-(void)rotationAction:(UIRotationGestureRecognizer*)sender  
{  
    //手勢作用的視圖  
    UIView *myView = [sender view];  
      
    //通過2D仿射變換函數(shù)與旋轉(zhuǎn)相關(guān)的函數(shù)對(duì)視圖旋轉(zhuǎn)  
    //第一個(gè)參數(shù):作用視圖的transfrom  
    //第二個(gè)參數(shù):旋轉(zhuǎn)的角度  
    float rotation = sender.rotation;  
    myView.transform = CGAffineTransformRotate(myView.transform, rotation);  
      
    //myView.transform = CGAffineTransformMakeRotation(M_PI_2);  
    //每進(jìn)行一次旋轉(zhuǎn),都需要將旋轉(zhuǎn)角度復(fù)原,讓其在原有基礎(chǔ)上再次累加  
    sender.rotation = 0;  
}  
  
//實(shí)現(xiàn)代理方法,可以同時(shí)響應(yīng)多個(gè)手勢  
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer  
{  
    return YES;  
}  
  
@end  
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容