Programmatically display keyboard in UIWebView

2019-08-04 13:16发布

问题:

If an element in a UIWebView has the style property -webkit-user-modify:read-write, then pressing on the element causes the keyboard to appear. Is it possible to bring up the keyboard programatically?

Thanks

回答1:

It looks like in iOS6 now you can do this with "keyboardDisplayRequiresUserAction":

keyboardDisplayRequiresUserAction A Boolean value indicating whether web content can programmatically display the keyboard.

@property (nonatomic) BOOL keyboardDisplayRequiresUserAction Discussion When this property is set to YES, the user must explicitly tap the elements in the web view to display the keyboard (or other relevant input view) for that element. When set to NO, a focus event on an element causes the input view to be displayed and associated with that element automatically.

The default value for this property is YES.

Availability Available in iOS 6.0 and later. Declared In UIWebView.h

reference:



回答2:

From iOS Developer Library:

Because the keyboard is displayed automatically when a view becomes the first responder, you often do not need to do anything to display it. However, you can programmatically display the keyboard for an editable text view by calling that view’s becomeFirstResponder method. Calling this method makes the target view the first responder and begins the editing process just as if the user had tapped on the view.

I doubt that calling [webView becomeFirstResponder] will bring up the keyboard as long as no HTML element with the required style has the focus. So your real problem might be to set the focus in your HTML document to an element programmatically. I would try to do this via Javascript. Something like this might work:

NSString *jscode = @"document.getElementById('whatever').focus();";
[self.webView stringByEvaluatingJavaScriptFromString:jscode];