Emre Önder
Emre Önder

Reputation: 2537

TouchesBegan always returns wrong UIView

I want to detect when I'm touching somewhere else rather than a specific UIView. I'm using touchesBegan for it, however, it always prints "touch is outside" (see code below). What am I missing?

I got help from this 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)
}

Anchors added inside ViewDidLoad Function

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) }

EDIT: ContainerView is a custom UIView which has some UIStackViews, UIlabels and UIImageViews in it. I found that It is because a custom UIView, when I change it with a regular UIView. It is working.

Upvotes: 1

Views: 204

Answers (1)

KLD
KLD

Reputation: 160

Try adding UIGestureRecognizer to the views you want to be detected on touch:

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
}

Alternatively, you can loop through all the subviews of parent view and exclude whatever views you want to exclude, like so:

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

Upvotes: 1

Related Questions