我想检测何时触摸其他地方而不是特定的 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,UIlabel
和 UIImageView
就在里面。我发现是因为自定义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/