我想检测何时我正在触摸其他地方而不是特定的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
函数中添加的锚点
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
,UIlabel
和UIImageView
。我发现这是因为自定义UIView
在我用常规UIView
进行更改时所致。它正在工作。
答案 0 :(得分:0)
尝试将UIGestureRecognizer添加到要在触摸时检测到的视图:
printf("Leaving MATLAB \n");
或者,您可以遍历父视图的所有子视图,并排除要排除的任何视图,例如:
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
}