Search code examples
iphoneiosuiimageviewuitouchuitapgesturerecognizer

Click Event on UIImageView programmatically in ios


I am displaying a image from code here is the code

UIImageView *preArrowImage =[[UIImageView alloc]init ];
preArrowImage.image =[UIImage imageNamed:@"arrowprev.png"];
preArrowImage.frame = CGRectMake(20, 60, 10, 30);
[self.view addSubview:preArrowImage];

I want to handle the touch event on the preArrowImage programmatically.


Solution

  • SWIFT 5

    let preArrowImage : UIImageView // also give it frame
    let singleTap = UITapGestureRecognizer(target: self, action: #selector(tapDetected))
    preArrowImage.isUserInteractionEnabled = true
    preArrowImage.addGestureRecognizer(singleTap)
    
    //Action
     func tapDetected() {
        print("Imageview Clicked")
    }
    

    Objective-c

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
    singleTap.numberOfTapsRequired = 1;
    [preArrowImage setUserInteractionEnabled:YES];
    [preArrowImage addGestureRecognizer:singleTap];
     
    -(void)tapDetected{
        NSLog(@"single Tap on imageview");
      }