How can I get a UIWebView to focus on a form input and bring up the keyboard?

假装没事ソ 提交于 2019-11-27 02:59:40

问题


I've created a UIWebView for logging into Facebook's Graph API OAuth interface. This works great, but I have to tap the first input field in order for the keyboard to pop up. Ideally, the keyboard would appear as soon as the form appears. So I've been trying to figure out how to make the first form field get the focus from the webViewDidFinishLoad: UIWebViewDelegate method, like so:

- (void)webViewDidFinishLoad:(UIWebView *)wv {
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('email')[0].focus();"];
}

Alas, this does not work. Curiously, when I run that JavaScript in the Firefox JavaScript console, it does move the focus to the email field. When I run it in Safari for the Mac, however, it does nothing, just like on iOS. FWIW, alert(document.getElementsByName('email')[0]) does show that it selects an HTMLInputElement. So why does focus() do nothing either in iOS or Mac OS X?


回答1:


This is now possible with iOS 6.

UIWebView* webView = <#your webView here#>;
[webView setKeyboardDisplayRequiresUserAction:NO];
[webView loadHTMLString:@"<html><head></head><body><form><input id=\"textField\" /></form><script>document.getElementById(\"textField\").focus();</script></body></html>"
                baseURL:nil];



回答2:


As soumya92 points out in the comment to the original post, this post finds that it's not possible at this time. Alas.



来源:https://stackoverflow.com/questions/4442811/how-can-i-get-a-uiwebview-to-focus-on-a-form-input-and-bring-up-the-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!