Search code examples
iosswiftuiviewuitapgesturerecognizer

Swift: Gesture Recognizer doesn't register Taps after changing alpha to 0 and back to 1


the UIView in question is headerView:

    if isShown {
        stack.alpha = 1.0
        self.isStackShown = true
        DispatchQueue.main.async {
            self.headerView.isHidden = !isShown
            self.stack.addArrangedSubview(self.headerView)

            // add touch gesture recognizer to stack view header
            let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
            self.headerView.addGestureRecognizer(tapFind)
        }
    } else {
        stack.alpha = 0.0
        self.isStackShown = false
        DispatchQueue.main.async {
            self.headerView.isHidden = isShown
            self.stack.removeArrangedSubview(self.headerView)
        }
    }

The tap gesture recognizer is not registering any taps
self.stack is the stack view which contains the headerView
The condition for either showing or hiding the headerView is being handled in a different method and just passes the boolean self.isStackShown to this method to show/hide accordingly.


Solution

  • You are using a UIGestureRecognizer. UIGestureRecognizer is a polymorphic base class and should really be subclassed. UITapGestureRecognizer is the concrete subclass for handling taps. Use it instead.

    let tapFind = UITapGestureRecognizer(target: self, action: #selector(self.handleFindTap))
    self.headerView.addGestureRecognizer(tapFind)
    

    Your action is never getting called because UIGestureRecognizer has no inherent information about what kind of gesture to recognize. Only a concrete subclass of it does.