Click Event on UIImageView programmatically in ios

Sumit Patel picture Sumit Patel · Jun 15, 2013 · Viewed 90.9k times · Source

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.

Answer

Vivek Sehrawat picture Vivek Sehrawat · Jun 15, 2013

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");
  }

SWIFT 4.2/5

let preArrowImage : UIImageView // also give it frame
let singleTap = UITapGestureRecognizer(target: self, action: #selector(tapDetected))
preArrowImage.isUserInteractionEnabled = true
preArrowImage.addGestureRecognizer(singleTap)

//Action
@objc func tapDetected() {
    print("Imageview Clicked")
}