How to identify touch on a specific imageView from

2019-05-31 08:33发布

I have multiple ImageViews in a UIScrollView and I want to identify the specific imageView on which I touched. So that I could do some actions. (for example, showing Alert with the image name).

I have seen some similar posts, but they did not have proper answer. And some answers were complex to me as I am pretty new to iPhone programming.

It would be great, If anybody helps with a simple example. :-)

my code is like this

- (void)viewDidLoad {   


imgScrollView.userInteractionEnabled =YES;

// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= 5; i++)
{
    NSString *imageName = [NSString stringWithFormat:@"image%d.jpg", i];
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    // setup each frame to a default height and width
    CGRect rect = imageView.frame;
    rect.size.height = kHeight;
    rect.size.width = kWidth;
    imageView.frame = rect;
    imageView.tag = i;  

    [imgScrollView addSubview:imageView];

    [imageView release];
}


[self layoutImages];

[super viewDidLoad];
}

     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// WHAT CODE SHOULD I GIVE HERE ?????????? :-)

}

3条回答
太酷不给撩
2楼-- · 2019-05-31 09:04

I recommend you look through the documentation and examples for UIGestureRecognizer. There is also a more explanatory Event Handling Guide .

This will walk you through adding Gesture Recognizers to specific views (e.g. your imageView) that can handle swipes, taps and multitouch gestures however you like.

查看更多
疯言疯语
3楼-- · 2019-05-31 09:15

You can use UIButton instead of image view. Assign tags for each button and then identify them using switch(...).

查看更多
Explosion°爆炸
4楼-- · 2019-05-31 09:17

Associate a unique tag value with each UIImageView instance:

In viewDidLoad or wherever your images are initialised:

myImageView1.tag = 1;
myImageView2.tag = 2;
myImageView3.tag = 3;

then try a gesture or something like:

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event       
{
UITouch *touch = [[event allTouches] anyObject];
int t = [touch view].tag;
UIImageView *imageView = (UIImageView *) [self.view  viewWithTag:t];
//your logic here since you have recognized the imageview on which user touched
}

haven't tried something like this before but it should probably work.

查看更多
登录 后发表回答