iphone - 如何检测图像是否被触摸

标签 iphone objective-c xcode image touch

在 Xcode 中如何检测图像是否被触摸?我看过 Apple 文档,它真的很困惑...... 我看到了:

if (CGRectContainsPoint([imageView frame], location))

但我的图像仍然不会移动。我尝试使用 touchesBegan + touchesMoved,并将图像的 userInteractionIsEnabled 设置为 YES,但它仍然检测不到它:(


编辑:非常感谢大家的宝贵建议!最后,我真的很想让它尽可能简单,而且我知道我的代码应该可以工作,所以我一直在摆弄它,睡了一觉后,我意识到这是一个相当简单的解决方案:

在我的 touchesMoved 中:

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    CGRect shapeRect = [imageView frame];
    CGRect dropSquareRect = [dropSquare frame];

    CGPoint touchLocation = CGPointMake(location.x, location.y);

    if (CGRectContainsPoint(shapeRect, touchLocation))
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:.3];
        [imageView setCenter:touchLocation];
        [UIView commitAnimations];
    }

    if (CGRectIntersectsRect(shapeRect, dropSquareRect))
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        self.imageView.alpha = 0;
        self.imageView.center = CGPointMake(dropSquare.center.x, dropSquare.center.y);
        self.imageView.transform = CGAffineTransformMakeScale(0.8, 0.8);
        [UIView commitAnimations];

最佳答案

您可以考虑使用 UITapGestureRecognizerUIImageView 来检测触摸。

并且不要忘记将 userInteractionIsEnabled 设置为 YES

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self              action:@selector(imageTapped:)];
myImageView.userInteractionIsEnabled = YES;
[myImageView addGestureRecognizer:tap];
[tap release];

实现 imageTapped: 方法。

- (void )imageTapped:(UITapGestureRecognizer *) gestureRecognizer 
   {

   }

关于iphone - 如何检测图像是否被触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6577705/

相关文章:

iphone - Xcode源码自动格式化

ios - 在 Swift 中访问 plist(错误 : "Expressions are not allowed at the top level")

iphone - 将字符串转换为 NSDate 问题 : [__NSDate Length] unrecognized selected

ios - Xcode 运行成功但归档时出错

ios - Cocos2d-x 4.0新项目不包含xcodeproj文件

ios - 尝试运行时出错 `pod trunk push [cocoapod].podspec`

ios - 如何使 AVPlayer 随父 View 调整大小?

objective-c - 如何让我的 MPMoviePlayerController 横向播放?

ios - Xcode 4.3 - 为临时测试制作存档不起作用

ios - 设置子 Pane 的值