UIGestureRecognizer,手勢處理,點選,長按,拖動,左右划動
阿新 • • 發佈:2019-02-09
對於移動端,由於使用者都是通過手指觸控來操作的,所以對於手勢的處理是必不可少的。下面詳細談談有哪幾種手勢操作。
1.點選,長按,拖動,左劃,右劃(上劃下劃)。
2.閒話不多說,直接看程式碼。程式碼Demo地址:https://github.com/gujinyue1010/iOS_UIGestureRecognizer
#import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIImageView *imageView1; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.imageView1.userInteractionEnabled=YES; //1.點選手勢 //建立手勢例項 UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapGesture)]; //設定手勢點選數(不設定預設是一次) //tapGesture.numberOfTapsRequired=2; //為imageView1新增手勢識別 [self.imageView1 addGestureRecognizer:tapGesture]; //2.長按手勢 UILongPressGestureRecognizer *longPressGesture=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPressGesture)]; longPressGesture.minimumPressDuration=1.0; [self.imageView1 addGestureRecognizer:longPressGesture]; //3.拖手勢 UIPanGestureRecognizer *panGesture=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanGesture:)]; [self.imageView1 addGestureRecognizer:panGesture]; //4.左劃手勢(整個螢幕給個划動手勢) UISwipeGestureRecognizer *swipeLeftGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)]; swipeLeftGesture.direction=UISwipeGestureRecognizerDirectionLeft; [self.view addGestureRecognizer:swipeLeftGesture]; //5.右劃手勢 UISwipeGestureRecognizer *swipeRightGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)]; swipeRightGesture.direction=UISwipeGestureRecognizerDirectionRight; [self.view addGestureRecognizer:swipeRightGesture]; } -(void)handleTapGesture { NSLog(@"雙擊了圖片"); } -(void)handleLongPressGesture { NSLog(@"長按了圖片"); } -(void)handlePanGesture:(UIPanGestureRecognizer *)sender { //平衡 CGPoint netTranslation; //得到拖過程中的xy座標 CGPoint translation=[(UIPanGestureRecognizer *)sender translationInView:self.imageView1]; //平移圖片 sender.view.transform=CGAffineTransformMakeTranslation(netTranslation.x+translation.x, netTranslation.y +translation.y); if(sender.state==UIGestureRecognizerStateEnded) { netTranslation.x+=translation.x; netTranslation.y+=translation.y; } NSLog(@"在拖動"); } -(void)handleSwipeGesture:(UISwipeGestureRecognizer *)sender { NSLog(@"%lu",(unsigned long)sender.direction); if(sender.direction==UISwipeGestureRecognizerDirectionUp) { NSLog(@"向上"); } else if(sender.direction==UISwipeGestureRecognizerDirectionLeft) { NSLog(@"向左"); } else if(sender.direction==UISwipeGestureRecognizerDirectionDown) { NSLog(@"向下"); } else if(sender.direction==UISwipeGestureRecognizerDirectionRight) { NSLog(@"向右"); } }