【问题标题】:How to add gesture recognizer to a UIImageview?如何将手势识别器添加到 UIImageview?
【发布时间】:2012-09-09 12:14:56
【问题描述】:

在项目中,myView 后面有一个UIViewmyView 和一个UIImageViewmyImage,视图层次结构:

UIWindow
|-- UIImageView (myImage)
|-- UIView (myView) [全屏]

然后在 ViewController 的 myImage 中添加手势识别器

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        tapGesture.numberOfTapsRequired = 1;
        [myImage addGestureRecognizer:tapGesture];

但是手势不影响myImage,myImage有setUserInteractionEnabled:YES。只有当myImage放在myView前面时才会有影响,请问如何解决?

【问题讨论】:

  • 如果它在视图后面,它将不会收到触摸。

标签: ios uiview uigesturerecognizer


【解决方案1】:

您的UIView 显然会在触摸到达UIImageView 之前拦截它们。

您可以将UIImageView 放在UIView 前面,或者禁用UIView 上的用户交互,这样它就不会拦截触摸。

如果您需要更精细地捕捉触摸事件,您可以:

  • 如果出于设计目的必须将UIView 放在UIImageView 之上(例如,如果它掩盖了UIImageView 一点)但使其不捕获事件(userInteractionEnabled = NO),并使用UIImageView 下方的不同 UIView 以实际捕获 UIImageView 之外的事件
  • 将您的UIView 保持在UIImageView 之上并保持它捕获事件(userInteractionEnabled = YES),但是通过子类化您的UIView 并覆盖pointInside:withEvent: 或hitTest:withEvent: 方法。

欲了解更多信息你真的应该阅读the dedicated Apple Programming Guide related to Event Handling。

【讨论】:

  • 但是 myImage 必须留在 myView 后面,有没有办法可以在触摸开始时进行检测并确定哪个视图会受到影响?
  • 是的。正如我在回答中所说,在 UIView 上关闭用户交互 (userInteractionEnabled = NO)。如果UIView 仍然需要在除UIImageView 所在的位置之外的任何地方捕获触摸事件,那么您有多种可能性:(1)将您的UIView 放在UIImageView 的顶部,但使用userInteractionEnabled = NO 并放置另一个@987654346 @ 在UIImageView 下方,捕获UIImageView 未捕获的每个触摸事件或(2)将UIView 放在UIImageView 之上,对其进行子类化并覆盖hitTest:withEvent: 或@987654352 @UIView 方法
【解决方案2】:

我的代码:

UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc] 
initWithTarget:self action:@selector(hasLongPressed)];
[press setMinimumPressDuration:0.1f]; //1ms
press.delegate = (id)self;
[self.DGEMLogo addGestureRecognizer:press];

需要两个属性

1.) 将 GestureRecognizer 添加到您的 UIImageView (self.DGEMLogo) [self.DGEMLogo addGestureRecognizer:press];

2.) 将您的 UIImage 属性 Interaction enabled 设置为 TRUE

仅此而已。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多