iOS-为UIView、UILabel、UIImageView添加手势

iOS-为UIView、UILabel、UIImageView添加手势

说明 : 

1.手势不能被重复使用,手势定义后只能对最后一个使用它的视图生效,例如1个手势先后被UILabel1,UILabel2,UILabel3 三个标签添加( label1 addGestureRecognizer:手势),那么只有最后添加手势的UILabel3的手势生效,而先添加手势的UILabel1、UILabel2的手势将不起作用。

2.UILabel、UIImageView添加手势后,必须将其属性userInteractionEnabled设置为YES,而UIIView则不需要,因为UIView的属性userInteractionEnabled默认就是YES。

//定义手势1
    UITapGestureRecognizer* gesture1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doClick:)];
    //定义手势2
    UITapGestureRecognizer* gesture2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doClick:)];
    //定义手势3
    UITapGestureRecognizer* gesture3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doClick:)];
   
    //为UILabel标签添加手势
    lblInfo.userInteractionEnabled=YES;//必须设置为YES [UILabel的userInteractionEnabled默认为NO]
    [lblInfo addGestureRecognizer:gesture1];
   
    //为UIImageView添加手势
    ivInfo.userInteractionEnabled=YES;//必须设置为YES [UIImageView的userInteractionEnabled默认为NO]
    [ivInfo addGestureRecognizer:gesture2];
   
    //为UILabel和UIImageView的父视图UIView添加手势
    [viewInfo addGestureRecognizer:gesture3];//[UIView的userInteractionEnabled默认为YES]

 -(void) doClick : (UITapGestureRecognizer*) sender{
    UIView* view = sender.view;
    NSLog(@"doClick:%@",[view description]);
}

猜你喜欢

转载自stephen830.iteye.com/blog/2248319