为什么 hitTest(_:with:) 不与以编程方式添加的 UIImageView 交互

Why doesn't hitTest(_:with:) interact with programmatically added UIImageView

当以编程方式添加时,我无法让 hitTest(_:with:) 遍历 UIImageView。

在 IB 中,我制作了一个正方形区域并将其标记为 1。在该正方形中,我插入了一个 UIImageView (tag=2)(orange/white 在下面的屏幕截图中)。在 ViewController 中,我以编程方式创建了另一个正方形 (tag=3)。然后在其中添加一个 UIImageView(tag=4)(下面屏幕截图中的red/green)。下图显示了这一点:

我正在使用 touchesBegan(_:with:) 来执行 hitTest。当我触摸橙色时,我得到了带有标签 1(预期)的视图的打印输出。如果我触摸白色方块,我会得到带有标签 2(预期)的打印输出。这些是在 IB 中创建的。

当我触摸红色方块时,我得到标签 3(预期)。当我触摸绿色时,我得到标签 3! (预计不会)。我查看了运行时层次结构,没有发现 IB 和编程之间的结构有任何差异。 hitTest(_:with:) 似乎没有 recognize/traverse/include/detect 程序化 UIImageView。有什么区别?

这是我的 ViewController 代码:

import UIKit

class ViewController: UIViewController {

  @IBOutlet var gameView: UIView!
  @IBOutlet var boardView: UIImageView!

  var g2 : UIView!
  var b2 : UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()

    g2 = UIView(frame: CGRect(x: 100, y: 50, width: 240, height: 240))
    g2.backgroundColor = .red
    g2.tag = 3
    view.addSubview(g2)

    b2 = UIImageView(frame: CGRect(x: 75, y: 75, width: 80, height: 80))
    b2.backgroundColor = .green
    b2.tag = 4
    g2.addSubview(b2)
  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if event!.type != .touches { return }

    if let first = touches.first {
      let loc = first.location(in: view)
      if let v = view.hitTest(loc, with: nil) {
        print("\(v)")
      }
    }
  }

}

我已将程序化的 UIImageView 更改为 UIView,hitTest 已按预期检测到它。

UIImageView 默认将 isUserInteractionEnabled 设置为 false,例如它没有收到任何触摸。

故事板也应如此,可能您启用了 User Interactions Enabled 复选标记。

大多数其他视图默认将此 属性 设置为 true,但如果您想与 UIImageView 触摸交互,则需要明确启用它。

b2.isUserInteractionEnabled = true