检测UIImageView上的触碰事件

ton*_*ran 3 iphone

我在UIView上放置了4个UIImageView,并将它命名为

UIImageView myImg1 = [[UIImageView alloc] init];     
UIImageView myImg2 = [[UIImageView alloc] init];     
UIImageView myImg3 = [[UIImageView alloc] init]; 
UIImageView myImg4 = [[UIImageView alloc] init];
Run Code Online (Sandbox Code Playgroud)

我怎么能告诉编译器我刚刚触及UIImageView 1或UIImaveView 2.如果我只能使用UIImageView来完成这个任务,而不是按钮.请指导我这个问题.谢谢

val*_*ine 6

一个时尚的解决方案是使用UIGestureRecognizer对象:

在你的loadView方法中(或你编写UIImageView(s)绘图的任何地方......):

   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];
Run Code Online (Sandbox Code Playgroud)

这是一个简单的imageViewDidTapped: sample方法,可用于区分上面的两个示例UIImageView对象:

- (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;
    }
}
Run Code Online (Sandbox Code Playgroud)