【问题标题】:Why doesn't hitTest(_:with:) interact with programmatically added UIImageView为什么 hitTest(_:with:) 不与以编程方式添加的 UIImageView 交互
【发布时间】:2021-11-02 11:26:45
【问题描述】:

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

在 IB 中,我创建了一个正方形区域并为其指定标签 1。在该正方形中,我插入一个 UIImageView (tag=2)(下面的屏幕截图中的橙色/白色)。在 ViewController 中,我以编程方式创建另一个正方形(tag=3)。然后在其中添加一个 UIImageView(tag=4) (下面的屏幕截图中的红色/绿色)。下图显示了这一点:

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

当我触摸红色方块时,我得到标签 3(预期)。当我触摸绿色时,我得到标签 3! (不是预期的)。我查看了运行时层次结构,并没有看到 IB 和编程之间的结构有任何区别。 hitTest(_:with:) 似乎无法识别/遍历/包含/检测程序化 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 检测到。

【问题讨论】:

    标签: ios swift uiimageview


    【解决方案1】:

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

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

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

    b2.isUserInteractionEnabled = true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-31
      • 2012-08-04
      • 2012-11-30
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      相关资源
      最近更新 更多