ios - TouchesBegan 总是返回错误的 UIView

标签 ios swift uiview uikit

我想检测何时触摸其他地方而不是特定的 UIView 。我正在使用touchesBegan然而,对于它,它总是打印“触摸在外面”(参见下面的代码)。我错过了什么?

我从中得到了帮助post .

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let hitView = self.view.hitTest(touch.location(in: self.view), with: event)
        if hitView === checkBackContainer {
            print("touch is inside")
        } else {
            print("touch is outside")
        }
    }
    super.touchesBegan(touches, with: event)
}

ViewDidLoad内添加了 anchor 功能

private lazy var checkBackContainer = ImageUploadContainerView()

override func viewDidLoad(){
self.view.addSubview(checkBackContainer)
checkBackContainer.anchorCenterXToSuperview()
checkBackContainer.topAnchor.constraint(equalTo: checkFrontContainer.bottomAnchor, constant: 20).isActive = true
checkBackContainer.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 25).isActive = true
checkBackContainer.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -25).isActive = true
checkBackContainer.heightAnchor.constraint(equalTo: checkBackContainer.widthAnchor, multiplier: 0.42).isActive = true
checkBackContainer.layer.applySketchShadow(color: UIColor.white, alpha: 1.0, x: 0, y: 0.33, blur: 1, spread: 0, cornerRadius: 6)

let backTap = UITapGestureRecognizer(target: self, action: #selector(self.backContainerTapped(_:)))
checkBackContainer.addGestureRecognizer(backTap) }

编辑: ContainerView 是自定义的 UIView其中有一些UIStackView s,UIlabelUIImageView就在里面。我发现是因为自定义UIView ,当我用常规 UIView 更改它时。它正在工作。

最佳答案

尝试将 UIGestureRecognizer 添加到您想要在触摸时检测到的 View :

let tap = UITapGestureRecognizer(target: self, action: #selector(didTap(sender:)))
view1.addGestureRecognizer(tap)
view2.addGestureRecognizer(tap)

@objc func didTap(sender: UITapGestureRecognizer) {
//Perform whatever you want in here
}

或者,您可以循环遍历父 View 的所有 subview 并排除您想要排除的任何 View ,如下所示:

for view in self.view.subviews {
   if view != viewYouWantToExclude {
      view.addGestureRecognizer(tap)
   }
}

关于ios - TouchesBegan 总是返回错误的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53297970/

相关文章:

ios - child 浏览器 onLocationChange 不工作

ios - swift : Game starts to lag mid way

ios - Swift:以编程方式在一定距离内均匀地隔开 View ?

ios - 按钮标签在 XIB 支持的 View 中消失

Swift iOS - 当 TextField、TextView 和背景被点击但丢失事件时移除 View

ios - 如何在 iOS RSS 应用程序中显示解析后的 XML 中的图像?

ios - NSDateIntervalFormatter 打印日期,即使 dateStyle 设置为 NSDateFormatterNoStyle

ios - 自动布局 : constraint for the same height and width

ios - swift ,NSOperationQueue.mainQueue() : update data in operation during operation is running?

php - 将 json 对象检索到 xCode 中始终带有 nil 值