UISwipeGestureRecognizer ---手指动作(转)
tap是指轻触手势。类似鼠标操作的点击。从iOS 3.2版本开始支持完善的手势api:
- tap:轻触
- long press:在一点上长按
- pinch:两个指头捏或者放的操作
- pan:手指的拖动
- swipe:手指在屏幕上很快的滑动
- rotation:手指反向操作
这为开发者编写手势识别操作,提供了很大的方便,想想之前用android写手势滑动的代码(编写android简单的手势切换视图示例),尤其感到幸福。
这里写一个简单的tap操作。在下面视图的蓝色视图内增加对tap的识别:
当用手指tap蓝色视图的时候,打印日志输出:
代码很简单,首先要声明tap的recognizer:
1 UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapFrom:)]; 2 [infoView addGestureRecognizer:recognizer]; 3 [recognizer release];
在这里:
- initWithTarget:self,要引用到Controller,因为一般这部分代码写在controller中,用self;
- action:@selector(handleTapFrom:),赋值一个方法名,用于当手势事件发生后的回调;
- [infoView addGestureRecognizer:recognizer],为view注册这个手势识别对象,这样当手指在该视图区域内,可引发手势,之外则不会引发
对应的回调方法:
1 -(void)handleTapFrom:(UITapGestureRecognizer *)recognizer{ 2 NSLog(@">>>tap it"); 3 }
controller相关方法完整的代码(包含了一些与本文无关的视图构建代码):
1 // Implement loadView to create a view hierarchy programmatically, without using a nib. 2 - (void)loadView { 3 //去掉最顶端的状态拦 4 [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation: UIStatusBarAnimationSlide]; 5 6 UIImage *image=[UIImage imageNamed:@"3.jpg"]; 7 8 //创建背景视图 9 self.view=[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; 10 UIImageView *backgroudView=[[UIImageView alloc] initWithImage:image]; 11 [self.view addSubview:backgroudView]; 12 13 /* 14 UIToolbar *toolBar=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 1024-70, 768, 70)]; 15 toolBar.alpha=0.8; 16 toolBar.tintColor = [UIColor colorWithRed:.3 green:.5 blue:.6 alpha:.1]; 17 18 NSArray *items=[NSArray arrayWithObjects:[[UIBarButtonItem alloc] initWithTitle:@"test" style:UIBarButtonItemStyleDone target:self action:nil],nil]; 19 toolBar.items=items; 20 [self.view addSubview:toolBar]; 21 */ 22 23 UIView *bottomView=[[UIView alloc] initWithFrame:CGRectMake(0, 1024-70, 768, 70)]; 24 bottomView.backgroundColor=[UIColor grayColor]; 25 bottomView.alpha=0.8; 26 27 //UIButton *backButton=[[UIButton alloc] initWithFrame:CGRectMake(10, 10, 100, 40)]; 28 UIButton *backButton=[UIButton buttonWithType: UIButtonTypeRoundedRect]; 29 [backButton setTitle:@"ok" forState:UIControlStateNormal]; 30 backButton.frame=CGRectMake(10, 15, 100, 40); 31 32 [bottomView addSubview:backButton]; 33 34 [self.view addSubview:bottomView]; 35 36 UIView *infoView=[[UIView alloc] initWithFrame:CGRectMake(200, 700, 768-400, 70)]; 37 infoView.backgroundColor=[UIColor blueColor]; 38 infoView.alpha=0.6; 39 infoView.layer.cornerRadius=6; 40 infoView.layer.masksToBounds=YES; 41 [self.view addSubview:infoView]; 42 43 UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapFrom:)]; 44 [infoView addGestureRecognizer:recognizer]; 45 [recognizer release]; 46 } 47 48 -(void)handleTapFrom:(UITapGestureRecognizer *)recognizer{ 49 NSLog(@">>>tap it"); 50 }