Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

iphone - how to get the tag of the UIImageView I'm tapping?

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 ^_^

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:
    //...
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...