-->

programmatically handling a text field within a ui

2019-06-12 04:30发布

问题:

I have a webpage with a text field and a submit button. That webpage is loaded within a UIWebView.

How would I programmatically press the submit button for that webpage?

Alternatively, how would I programmatically make the text field within the webpage the first responder and display the soft keyboard? Just programmatically re-create the same behavior as if the user had touched the text field on the webpage.

I would like to make the assumption that the source of the page is unknown.

This is not a UITextField it is just a within the webpage that is displayed in a UIWebView.

Thanks in advance.

回答1:

If you know the source of the page, you can use UIWebView's stringByEvaluatingJavascriptFromString. For example:

NSString *focusTextField = @"document.getElementById('textFieldID').focus();";
[webView stringByEvaluatingJavascriptFromString:focusTextField];



回答2:

I'm not sure if my question was clear, but this was the answer that worked for me:

jScriptString = [NSString stringWithFormat:@"var field = document.activeElement;" 
                     "field.value='%@';", symbol.data];
    [myWebView stringByEvaluatingJavaScriptFromString:jScriptString];
    jScriptString = [NSString stringWithFormat:@"document.activeElement.form.submit();"];
    [myWebView stringByEvaluatingJavaScriptFromString:jScriptString];