How to identify touch on a specific imageView from multiple imageViews in a UIScrollView?

纵饮孤独 提交于 2020-01-03 03:12:07

问题


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 ?????????? :-)

}

回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/6208217/how-to-identify-touch-on-a-specific-imageview-from-multiple-imageviews-in-a-uisc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!