Sumit Patel Sumit Patel - 5 months ago 133
iOS Question

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.

Answer

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

let singleTap = UITapGestureRecognizer(target: self, action:"tapDetected:")
singleTap.numberOfTapsRequired = 1
preArrowImage.userInteractionEnabled = true
preArrowImage.addGestureRecognizer(singleTap)

func tapDetected() {
    println("Single Tap on imageview")
}

SWIFT - 2

Replace Selector("tapDetected") with: "tapDetected:"

SWIFT - 2.2

Replace "tapDectected:" with #selector(className.tapDetected)