Search code examples
iosswiftwebviewuiwebviewuitapgesturerecognizer

(Swift) Handling user's tap on webView


I have webView and a hidden stackView(3 buttons) in the bottom of webView on my screen.

@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var stackView: UIStackView!

By default, stackView is hidden, and it should be visible when user taps somewhere on the webView.

override func viewDidLoad() {
        super.viewDidLoad()
        stackView.isHidden = true
    }

How can I handle user's tap to make my 'stackView' visible?


Solution

  • You can use UITapGestureRecognizer, try this

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tapGesture.delegate = self
        webView.addGestureRecognizer(tapGesture)
       } 
    
      @obj func handleTap() {
          stackView.isHidden = false
        }
    

    don't forget to add UIGestureRecognizerDelegate

    if it doesn't work, you have to add following method because WKWebView already has its own gesture recognizers

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
      return true
    }