Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect a touch down event on UIImageView(s)

Tags:

iphone

I placed 4 UIImageView on UIView and I named them

UIImageView myImg1 = [[UIImageView alloc] init];     
UIImageView myImg2 = [[UIImageView alloc] init];     
UIImageView myImg3 = [[UIImageView alloc] init]; 
UIImageView myImg4 = [[UIImageView alloc] init];

How can I tell the compiler that I have just touched down UIImageView 1 or UIImaveView 2. If I only can use UIImageView to do this task, not buttons at all. Please guide me about this issue. Thanks

like image 639
tonytran Avatar asked Dec 30 '25 16:12

tonytran


1 Answers

A stylish solution is to use the UIGestureRecognizer object:

in your loadView method (or anywhere you code the UIImageView(s) drawing...):

   UITapGestureRecognizer *tapRecognizer;
    UIImageView *anImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
    [anImageView setTag:0]; //Pay attention here!, Tag is used to distinguish between your UIImageView on the selector
    [anImageView setBackgroundColor:[UIColor redColor]];
    [anImageView setUserInteractionEnabled:TRUE];
    tapRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDidTapped:)] autorelease];
    tapRecognizer.numberOfTapsRequired = 1;
    [anImageView addGestureRecognizer:tapRecognizer];
    [contentView addSubview:anImageView];
    [anImageView release];

    UIImageView *anotherImageView = [[UIImageView alloc] initWithFrame:CGRectMake(80, 180, 100, 100)];
    [anotherImageView setTag:1]; //Pay attention here!, Tag is used to distinguish between your UIImageView on the selector
    [anotherImageView setBackgroundColor:[UIColor greenColor]];
    [anotherImageView setUserInteractionEnabled:TRUE];
    tapRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDidTapped:)] autorelease];
    tapRecognizer.numberOfTapsRequired = 1;
    [anotherImageView addGestureRecognizer:tapRecognizer];
    [contentView addSubview:anotherImageView];
    [anotherImageView release];

This is a simple imageViewDidTapped: sample method that you can use to distinguish between the two sample UIImageView objects above:

- (void)imageViewDidTapped:(UIGestureRecognizer *)aGesture {
    UITapGestureRecognizer *tapGesture = (UITapGestureRecognizer *)aGesture;

    UIImageView *tappedImageView = (UIImageView *)[tapGesture view];

    switch (tappedImageView.tag) {
        case 0:
            NSLog(@"UIImageView 1 was tapped");
            break;
        case 1:
            NSLog(@"UIImageView 2 was tapped");
            break;
        default:
            break;
    }
}
like image 192
valvoline Avatar answered Jan 02 '26 05:01

valvoline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!