gpt4 book ai didi

iphone - 使用 UITapGestureRecognizer

转载 作者:太空狗 更新时间:2023-10-30 03:59:12 27 4
gpt4 key购买 nike

iPhone 开发新手。我有一个 View ,其中包含一个包含 UIImageView 的 UIScrollView。我在 ImageView 上添加了一个(双击)点击手势识别器,它打开了一个警告框。出于某种原因,我确定我只是智障,它打开了 3 次。

这是我的代码:

- (void)viewDidLoad {

scrollView.delegate = self;

UIImage* image = imageView.image;
imageView.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
scrollView.contentSize = image.size;

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
tapGesture.numberOfTapsRequired = 2;
[imageView addGestureRecognizer:tapGesture];
[tapGesture release];

NSLog(@"LOADED");

[super viewDidLoad];
}

-(IBAction) handleTapGesture:(UIGestureRecognizer *) sender {
CGPoint tapPoint = [sender locationInView:imageView];
int tapX = (int) tapPoint.x;
int tapY = (int) tapPoint.y;
NSLog(@"TAPPED X:%d Y:%d", tapX, tapY);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"How are you?" delegate:nil cancelButtonTitle:@"I'm awesome." otherButtonTitles:nil];
[alert show];
[alert release];
}

我几天前才开始 iPhone 开发。这个问题让我想起了我在 javascript 中处理过的事件冒泡问题。有什么想法吗?

最佳答案

不确定确切原因是什么,但 UIAlertView 以某种方式导致手势再次触发。解决方法是使用 performSelector 在手势处理程序外部执行显示:

-(void) handleTapGesture:(UIGestureRecognizer *) sender {
CGPoint tapPoint = [sender locationInView:imageView];
int tapX = (int) tapPoint.x;
int tapY = (int) tapPoint.y;
NSLog(@"TAPPED X:%d Y:%d", tapX, tapY);
[self performSelector:@selector(showMessage) withObject:nil afterDelay:0.0];
}

- (void)showMessage
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"How are you?" delegate:nil cancelButtonTitle:@"I'm awesome." otherButtonTitles:nil];
[alert show];
[alert release];
}

编辑:
手势识别器经历手势中的不同状态(开始、更改等),并在每次状态更改时调用处理程序方法。因此,一个更好且可能是正确的解决方案是检查处理程序顶部的手势识别器的状态属性:

-(void) handleTapGesture:(UIGestureRecognizer *) sender {
if (sender.state != UIGestureRecognizerStateEnded) // <---
return; // <---

CGPoint tapPoint = [sender locationInView:imageView];
int tapX = (int) tapPoint.x;
int tapY = (int) tapPoint.y;
NSLog(@"TAPPED X:%d Y:%d", tapX, tapY);

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"How are you?" delegate:nil cancelButtonTitle:@"I'm awesome." otherButtonTitles:nil];
[alert show];
[alert release];
}

关于iphone - 使用 UITapGestureRecognizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4001284/

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