K.Pilch K.Pilch - 6 months ago 37
iOS Question

Detect that user tap on screen Swift

i want to remove

from screen after user tap something except that view. (to visualize it for you I will upload sketch of my view)[

enter image description here]1

And I want to remove blue
after user tap on something except buttons in this view. What should I use?

In blue
are two buttons and I want to remove that view when user tap on background image

I did what "yerpy" told me to do but it isn't working.

func test(gestureRecognizer: UITapGestureRecognizer) {

func setUpBackgroundImageView() {
backgroundImageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
backgroundImageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
backgroundImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
backgroundImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let tap = UITapGestureRecognizer(target: self, action: #selector(test(gestureRecognizer:)))
tap.delegate = self

And I also add
function to
. What am I doing wrong?

Answer Source

Add UIGestureRecognizer to the super view :

As you said you have image view as a background.

 let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped(gestureRecognizer:)))
        tapRecognizer.delegate = self

Adding target action :

func tapped(gestureRecognizer: UITapGestureRecognizer) {
       // Remove the blue view.

And then inside UITapGestureRecognizerDelegate :

extension ViewController : UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view!.superview!.superclass! .isSubclass(of: UIButton.self) {
            return false
        return true

Hope it helps !


Make sure that user can touch on the view by enabling : self.view.userInteractionEnabled = true

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download