检测UIImageView上的触碰事件 [英] detect a touch down event on UIImageView(s)
问题描述
我在UIView上放置了4个UIImageView并将其命名为
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];
我如何告诉编译器我刚刚触及UIImageView 1或UIImaveView 2.如果我只可以使用UIImageView来执行此任务,而不是按钮。请指导我这个问题。谢谢
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
推荐答案
一个时尚的解决方案是使用 UIGestureRecognizer 对象:
A stylish solution is to use the UIGestureRecognizer object:
(或者你编码 UIImageView (s)绘图的任何地方......):
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];
这是一个简单的 imageViewDidTapped:示例方法,可用于区分上面的两个示例 UIImageView 对象之间:
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;
}
}
这篇关于检测UIImageView上的触碰事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!