首页 > 代码库 > 手势识别

手势识别

IOS设备上识别有两种方式:

1手势识别器(UIGestureRecognizer)

2触摸事件(UITouch)

新建工程,用singleViewApplication模版,工程名TapGestureRecognizer

然后从对象库中拉出ImageView到设计窗口

为了能够让用户接收事件,需要设置它userInteractionEnabled为开启。

打开工程viewController.h

 1 #import <UIKit/UIKit.h> 2  3 @interface ViewController : UIViewController{ 4     BOOL boolTrashEmptyFlag; 5 } 6 @property (strong,nonatomic)UIImage *imageTrashFull; 7 @property (strong,nonatomic)UIImage *imageTrashEmpty; 8 @property (weak, nonatomic) IBOutlet UIImageView *imageView; 9 - (IBAction)founTap:(id)sender;10 11 12 @end

其中boolTrashEmptyFlag,作为判断点击图片时,显示是空还是满。

viewControl.m

 1 #import "ViewController.h" 2  3 @interface ViewController () 4  5 @end 6  7 @implementation ViewController 8  9 - (void)viewDidLoad10 {11     [super viewDidLoad];12     // Do any additional setup after loading the view, typically from a nib.13     NSBundle *bundle=[NSBundle mainBundle];14     self.imageTrashFull=[[UIImage alloc] initWithContentsOfFile:[bundle pathForResource:@"Blend Ttrah" ofType:@"png"]];15     self.imageTrashEmpty=[[UIImage alloc]initWithContentsOfFile:[bundle pathForResource:@"Empty" ofType:@"png"]];16     boolTrashEmptyFlag=NO;17     self.imageView.image=self.imageTrashFull;18     UITapGestureRecognizer *tapRecognizer=[[UITapGestureRecognizer alloc]19                                            initWithTarget:self20                                            action:@selector(foundTap:)];21     tapRecognizer.numberOfTapsRequired=1;22     tapRecognizer.numberOfTouchesRequired=1;23     [self.imageView addGestureRecognizer:tapRecognizer];}24 -(void)foundTap:(UITapGestureRecognizer *)paramSender{25     if(boolTrashEmptyFlag){26         self.imageView.image=self.imageTrashFull;27         boolTrashEmptyFlag=NO;28     }else{29         self.imageView.image=self.imageTrashEmpty;30         boolTrashEmptyFlag=YES;31     }32 }33 34 - (void)didReceiveMemoryWarning35 {36     [super didReceiveMemoryWarning];37     // Dispose of any resources that can be recreated.38 }39 40 - (IBAction)founTap:(id)sender {41 }42 @end

完成。

还有长按手势

代码跟点击差不多

UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc]                                           initWithTarget:self
 1 -(void)foundTap:(UITapGestureRecognizer *)paramSender{ 2 if(paramSender.state==UIGestureRecognizerStateBegan){ 3     if(boolTrashEmptyFlag){ 4         self.imageView.image=self.imageTrashFull; 5         boolTrashEmptyFlag=NO; 6     }else{ 7         self.imageView.image=self.imageTrashEmpty; 8         boolTrashEmptyFlag=YES; 9     }10 }11 }12 注:stage=1为长按开始,3则为长按结束

 

                                           action:@selector(foundTap:)];    recognizer.allowableMovement=100.0f;recognizer.minimumPressDuration=1.0;    [self.imageView addGestureRecognizer:recognizer];

另一处不同