Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone UIWebView becomeFirstResponder

I have an UIWebView with an <input type="text"/> html element in it. I want to focus the input element in the html and show the keyboard on the iPhone programmatically, without tapping the screen.

I've tried the following:

  • set the focus from JavaScript (in this case the onFocus JS event will fire but the keyboard won't show up)
  • [webView becomeFirstresponder] (returns NO)
  • set the first subview of the webView to be the firstResponder (returns NO)
  • subclass UIWebView to return YES to canBecomeFirstResponder: (nothing happens)

I'm trying to find the solution since yesterday but I couldn't find it. Please help.

like image 875
user505618 Avatar asked Nov 12 '10 10:11

user505618


1 Answers

In iOS6 or above, you have to set keyboardDisplayRequiresUserAction to NO first:

- (void)webViewDidFinishLoad:(UIWebView *)webView 
{
    webView.keyboardDisplayRequiresUserAction = NO;
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"theElementId\").setFocus();"]; 
}
like image 101
OpenThread Avatar answered Sep 28 '22 10:09

OpenThread