How to dismiss keyboard on a UIWebView?

15,074

Solution 1

You can use javascript to take the focus away from the HTML text field using blur:

document.foo.bar.myinput.blur();

Solution 2

A more concise way without needing to know what element is selected is the following:

[webView stringByEvaluatingJavaScriptFromString:@"document.activeElement.blur()"];

Solution 3

The javascript approach is clever, but this is more direct:

[webView endEditing:YES];

Solution 4

UIGestureRecogniser will help to dismiss the keyboard when user clicks on the WebView. Here is the piece of code i used.

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        tap.delegate = self 
        webView.addGestureRecognizer(tap)

@objc func handleTap(_ sender: UITapGestureRecognizer) { webView?.endEditing(true) }

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

Hope the helps.

Share:
15,074
Sheehan Alam
Author by

Sheehan Alam

iOS, Android and Mac Developer. i can divide by zero.

Updated on June 11, 2022

Comments

  • Sheehan Alam
    Sheehan Alam about 2 years

    I am loading an HTML page that has a form. I would like to be able to dismiss the keyboard when the user clicks on GO or if he clicks on the SUBMIT button on the HTML page.

    If the user decides he doesn't want to fill out the form, I also need a way to dismiss the keyboard.

    Not sure how to do this.