4

iPhone 开发新手。我有一个视图,其中包含一个 UIScrollView,其中包含一个 UIImageView。我在图像视图上添加了一个(双击)点击手势识别器,它打开了一个警告框。出于某种原因,我确定我只是智障,它打开了 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 中处理过的事件冒泡问题。有任何想法吗?

4

1 回答 1

10

不确定确切的原因是什么,但 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];
}

Edit:
The gesture recognizer goes through different states in the gesture (Began, Changed, etc) and it calls the handler method each time the state changes. So a better and probably correct solution is to check the state property of the gesture recognizer at the top of the handler:

-(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];
}
于 2010-10-22T22:28:59.743 回答