iOS:UIImageView新增點選事件
阿新 • • 發佈:2019-02-15
UIImageView並不像UIButton那樣點選滑鼠就可以關聯點選事件,也不像Android裡有onClickListener,這個時候就需要藉助UITapGestureRecognizer類,從類名上就可以看出,這個類就是用於處理tap(單擊)事件的。
建立兩個UIImageView物件,imageView1和imageView2
- [imageView1 setUserInteractionEnabled:YES];
- [imageView2 setUserInteractionEnabled:YES];
- [imageView1 addGestureRecognizer:[[UITapGestureRecognizer
- [imageView2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory:)]];
經測試,多個UIImageView不能共用一個UITapGestureRecognizer物件,之前呼叫的會沒效果。
根據點選的view判斷來自誰的點選
- -(void)clickCategory:(UITapGestureRecognizer
- {
- NSLog(@"click");
- NSLog(@"%hhd",[gestureRecognizer isMemberOfClass:[UITapGestureRecognizerclass]]);
- UIView*viewClicked=[gestureRecognizer view];
- if(viewClicked==imageView1){
- NSLog(@"imageView1");
- }elseif(viewClicked==imageView2)
- {
- NSLog(@"imageView2");
- }
- }