简体   繁体   中英

How to detect tap/click on UIImageView?

I'm trying to develop an app that has some images so I've done like:

@property (nonatomic, retain) IBOutletCollection(UIImageView)NSArray* photos;

and I'm filling these UIImageView array with :

[self.photos[i] setImage:[UIImage imageWithData:data]];

Now,I need to perform segue which will redirect the user to another view with the respect of which image is clicked.

Example :

Suppose I have 20 images and View, if user clicks 1st image then he should be redirected to view and if user clicks 2nd then the same view and so on...

I like to add mask-button over UIImageView to respond to the user touch, but notice that the userInteractionEnabled of UIImageView is NO by default.

Below is sample code, in practice we always set the button to transparent.

CGRect imageRect = (CGRect){100, 100, 100, 100};
UIImageView *imageView = [[[UIImageView alloc] initWithFrame:imageRect] autorelease];
imageView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:imageView];
imageView.userInteractionEnabled = YES;

UIButton *maskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
maskBtn.frame = imageView.bounds;
maskBtn.backgroundColor = [UIColor redColor];
[maskBtn addTarget:self action:@selector(maskBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
[imageView addSubview:maskBtn];

If you're using UIImageView's, then to handle tap, you'll have to create UITapGestureRecognizer's, give them a selector method, and add them to the imageViews, and handle the taps in the respective selectors.

A better way would be to use custom UIButtons instead of the UIImageView's and hook them up with actions directly from the storyboard/xib and handle the button press events in those actions. So you can prevent adding UITapGestures in each of the imageViews.

there are three ways
1) you can use TapGestures
2) You can Use UIControl & in UIControl add ImageView & give Selector to UIControl
3) add your Image to Custom UIButton

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM