1. 程式人生 > >iOS:UIImageView新增點選事件

iOS:UIImageView新增點選事件

UIImageView並不像UIButton那樣點選滑鼠就可以關聯點選事件,也不像Android裡有onClickListener,這個時候就需要藉助UITapGestureRecognizer類,從類名上就可以看出,這個類就是用於處理tap(單擊)事件的。

建立兩個UIImageView物件,imageView1和imageView2

  1. [imageView1 setUserInteractionEnabled:YES];
  2. [imageView2 setUserInteractionEnabled:YES];
  3. [imageView1 addGestureRecognizer:[[UITapGestureRecognizer
    alloc] initWithTarget:self action:@selector(clickCategory:)]];
  4. [imageView2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory:)]];

經測試,多個UIImageView不能共用一個UITapGestureRecognizer物件,之前呼叫的會沒效果。
根據點選的view判斷來自誰的點選

  1. -(void)clickCategory:(UITapGestureRecognizer
    *)gestureRecognizer
  2. {
  3. NSLog(@"click");
  4. NSLog(@"%hhd",[gestureRecognizer isMemberOfClass:[UITapGestureRecognizerclass]]);
  5. UIView*viewClicked=[gestureRecognizer view];
  6. if(viewClicked==imageView1){
  7. NSLog(@"imageView1");
  8. }elseif(viewClicked==imageView2)
  9. {
  10. NSLog(@"imageView2");
  11. }
  12. }
這樣就ok了