【问题标题】:Trouble using touchesEnded with a UIImageView使用带有 UIImageView 的 touchesEnded 时遇到问题
【发布时间】:2012-10-08 18:55:34
【问题描述】:

我一直在尝试使用touchedBegan 和touchedEnded。我基本上只是想在我的视图中创建一个图像。然后能够在用户触摸图像时做一些事情。当我触摸图像时,它确实会执行我的 if 语句中的代码。知道我做错了什么吗?

viewDidload:

UIImage *image = [UIImage imageNamed:@"myimage1.png"];
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, 320, 200);
[self.view addSubview:imageView];
imageViewsArray = [NSArray arrayWithObjects:imageView, nil];

touchesEnded:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];

    // do this on touch
    UIView *touchedView = [touch view];
    if ([imageViewsArray indexOfObject:touchedView] != NSNotFound) {
        // not not found means found!
        NSLog(@"Got Touch!");
    }
}

我也尝试过使用这个 if 语句:

if ([[touch view] isKindOfClass:[UIImageView class]]) {
        NSLog(@"Got Touch 2!");
}

【问题讨论】:

  • 查看我的帖子;我认为你的问题是你没有将 UIImageView 的属性 userInteractionEnabled 设置为 YES

标签: objective-c ios view touch


【解决方案1】:

就像 DrummerB 所说,我会推荐使用 UITapGestureRecognizer。查看官方文档here 以更好地了解它的工作原理,但主要是将手势识别器与将处理点击的视图相关联。在您的情况下,因为您正在处理UIImageView,请确保您打开属性userInteractionEnabled,默认情况下,NO 设置为NO:换句话说,imageView 默认情况下不接收事件.

【讨论】:

  • 太棒了,谢谢。如果我想更进一步,创建一个 UIScrollview 和一个 UIView 并将 UIImageView 放入其中,然后将 UIView 放入 UIScrollview 中。我的代码会选择它,还是我需要为此做一些子类化?
  • 发现了我自己,你确实需要子类化。因为 UIScrollView 不会调用我的 ViewController 中的方法,所以它会覆盖这些方法。所以我不得不继承 UIScrollView,然后覆盖这些方法。感谢您的帮助!
  • 刚刚看到你的消息 - 对不起,我不在了!
【解决方案2】:

如果您想在点击图像视图时收到通知,我建议您使用更简单的方法,使用 UITapGestureRecognizer

// After initializing and adding your UIImageView:
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self       
                               action:@selector(handleTap:)];
[imageView addGestureRecognizer:gr];

- (void)handleTap:(UITapGestureRecognizer *)gr {
    NSLog(@"Touched!");
}

如果您想坚持使用touchesEnded,请尝试以下步骤:

  • 检查您的imageViews数组是否不是touchesEnded中的nil
  • 登录 [touch view] 以查看哪个视图正在接收触摸。

【讨论】:

  • 谢谢!看起来我的 UIView 正在捕获触摸,但是如果我正在触摸 UIImageView 并且它被添加为 UIView 的子视图,会导致它这样做吗?
  • 是否调用了touchesEnded?当你触摸图像时会调用它吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
相关资源
最近更新 更多