detect a touch down event on UIImageView(s)

后端 未结 4 1484
北恋
北恋 2021-01-06 18:42

I placed 4 UIImageView on UIView and I named them

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


        
4条回答
  •  既然无缘
    2021-01-06 19:27

    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;
        }
    }
    

提交回复
热议问题