user1445685
user1445685

Reputation: 883

Touch on button is not detected when a TapGestureRecognizer is attached to the container view

In my app I have a viewcontroller which view has an attached tapGesture recognizer.

The tapGesture animated a hidden view (some kind of panel) which becomes visible. That view contains a button which can execute some action and then hides the panel.

But it seems like because of the tapgesture being attached to view-constroller's view, the touch on the button is not detected and only the tap on the view-controller view is fired.

I've tried playing with the firstResponder but doesn't seem to work

func addGesture(){
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(togglePanel))
    myView.addGestureRecognizer(tapGesture)
}

my panel is inseted like this:

 insertSubview(actionPanel, at: 0)

My button

actionPanel.addSubview(dismissBtn)

The button action

dismissBtn.addTarget(self, action: #selector(hideActionPanel), for: .touchUpInside)

@objc func hideActionPanel(){
        print("tapped")
    }

Upvotes: 0

Views: 1015

Answers (2)

Giorgio Doganiero
Giorgio Doganiero

Reputation: 143

You could add the UIGestureRecognizerDelegate to your class. To learn more go to UIGestureRecognizerDelegate.

Then implement the func gestureRecognizer(UIGestureRecognizer, shouldReceive: UITouch) -> Bool. This function will be called every time a gesture is about to happen. If you want to know exactly how it works go here gestureRecognizer.

Don't forget to connect your gesture to the delegate like this.

tapGesture.delegate = self

Finally, inside the UIGestureRecognizerDelegate function check if the view being touch equals to the view that has the gestureRecognizer. That will prevent any underlying views to recognize the gesture.

if touch.view == gestureRecognizer.view { return true } return false

Upvotes: 1

王永吉
王永吉

Reputation: 83

the button which doesn't seem to work

Run the app using xcode, Use Xcode "Debug View Hierarchy"

this button or it's superview may be .userInteractionEnabled = false

I assume that your animated image is a superview, and the image turns off user interaction by default

add this xxImage.userInteractionEnabled = true

Upvotes: 0

Related Questions