iOS:UIImageView添加点击事件
UIImageView并不像UIButton那样点击鼠标就可以关联点击事件,也不像Android里有onClickListener,这个时候就需要借助UITapGestureRecognizer类,从类名上就可以看出,这个类就是用于处理tap(单击)事件的。
创建两个UIImageView对象,imageView1和imageView2
- [imageView1 setUserInteractionEnabled:YES];
- [imageView2 setUserInteractionEnabled:YES];
- [imageView1 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory:)]];
- [imageView2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory:)]];
经测试,多个UIImageView不能共用一个UITapGestureRecognizer对象,之前调用的会没效果。
根据点击的view判断来自谁的点击
这样就ok了
- -(void)clickCategory:(UITapGestureRecognizer *)gestureRecognizer
- {
- NSLog(@"click");
- NSLog(@"%hhd",[gestureRecognizer isMemberOfClass:[UITapGestureRecognizer class]]);
- UIView *viewClicked=[gestureRecognizer view];
- if (viewClicked==imageView1) {
- NSLog(@"imageView1");
- }else if(viewClicked==imageView2)
- {
- NSLog(@"imageView2");
- }
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。