gpt4 book ai didi

iphone - 检测 UIImageView 上的触摸事件

转载 作者:行者123 更新时间:2023-12-03 19:32:01 27 4
gpt4 key购买 nike

我在 UIView 上放置了 4 个 UIImageView 并给它们命名

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

我如何告诉编译器我刚刚接触了 UIImageView 1 或 UIImaveView 2。如果我只能使用 UIImageView 来完成此任务,而根本不能使用按钮。请指导我解决这个问题。谢谢

最佳答案

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

在您的 loadView 方法中(或在您编写 UIImageView 绘图代码的任何地方...):

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

这是一个简单的 imageViewDidTapped: 示例方法,您可以使用它来区分上面的两个示例 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;
}
}

关于iphone - 检测 UIImageView 上的触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8976478/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com