Reputation: 446
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 ?????????? :-)
}
Upvotes: 1
Views: 711
Reputation: 593
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.
Upvotes: 0
Reputation: 48398
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.
Upvotes: 3
Reputation: 16719
You can use UIButton instead of image view. Assign tags for each button and then identify them using switch(...).
Upvotes: 1