i have several UIImageView, each of them has a tag; and I have an array of Images, what i want to do is: when user tap one of the UIImageView, the app give back the certain Image from array.
i implement like this:
- (void)viewDidLoad
{
[super viewDidLoad];
scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:scroll];
NSInteger i;
for (i=0; i<8; i++)
{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, i*100 + i*15, 300, 100)];
imageView.backgroundColor = [UIColor blueColor];
imageView.userInteractionEnabled = YES;
imageView.tag = i;
NSLog(@"%d", imageView.tag);
[scroll addSubview:imageView];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(findOutTheTag:)];
[imageView addGestureRecognizer:tap];
}
scroll.contentSize = CGSizeMake(320, 115*i);
}
- (void)findOutTheTag:(id)sender
{
// HOW TO FIND THE tag OF THE imageView I'M TAPPING?
}
I want find out the imageView.tag
, and pass imageView.tag
to
UIImageView *tappedImage = [imageArray objectAtIndex:imageView.tag];
to display the image.
I did tag all of them, question is how I can find out the tag
of the imageView I'm tapping? thank you for reading ^_^
At the risk of making a recommendation without seeing the full picture of your app, why not use a custom UIButton instead of UIImageViews for this? With a UIButton you can setup an action and pass the sender id, from which you can easily access your tags and pull the data from your array.
OR if you really want to use the above code and your know for a fact the - (void)findOutTheTag:(id)sender method is being called, all your have to do is:
- (void)findOutTheTag:(id)sender {
switch (((UIGestureRecognizer *)sender).view.tag)
{
case kTag1:
//...
case kTag2:
//...
}
}
Instead of using a UIImageView why don't you use an UIButton. That way you can simply add a listener for UITouchDown events. You can tag each button so that in your touchDown method you can find which button was pressed.
UIButton *button = [[UIImageView alloc] initWithFrame:CGRectMake(10, i*100 + i*15, 300, 100)];
button.backgroundColor = [UIColor blueColor];
button.tag = i;
[button addTarget:self action:@selector(touchDown:) controlEvent:UIControlEventTouchDown];
And inside of the touchDown: method you simply have to cast the sender to a UIButton in order to access the tag.
- (void)touchDown:(id)sender
{
UIButton* button = (UIButton*)sender;
switch(button.tag)
{
case TAG1:
break;
//etc
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With