0

我有一个UIWebView并且已经从服务器加载了一个文档。Web 文档有几个文本输入字段。如何确定用户触摸过的字段的 ID 或名称 - 已选择。然后我想分配一个值来填充输入字段。

我已经阅读了足够多的内容,相信我需要 JavaScript,但不知道如何将它与 Xcode 中的目标 c 相关联。任何帮助将不胜感激。

谢谢罗恩

4

1 回答 1

0

这是一个可以帮助您入门的简单实现的快速示例。

例子.html

<script type="text/javacript">
    function populateField(fieldId, fieldText) {
        $('#' + fieldId).val(fieldText);
    }

    var bridgeScheme = 'myapp';
    (function($) {
        $('#my-textfield').on('focus', function() {
            var data = {
                'action': 'focus',
                'field-id': $(this).attr('id')
            };
            var encodedData = encodeURIComponent(JSON.stringify(data));

            $('#iframe').attr('src', bridgeScheme + encodedData);
        });
    })(jQuery)
</script>

<form id="my-form">
    <div>
        <input type="text" id="my-textfield">
    </div>
</form>

<iframe src="" id="iframe"></iframe>

一些东西:

  • iframe用于生成将 通过UIWebView. 我们将能够通过 UIWebViewDelegate在控制器中实现来捕获它(见下文)
  • bridgeScheme变量是您如何能够检测到请求来自您自己的 javascript 代码(见下文)
  • populateField将从本机端调用 javascript 函数以使用您想要的任何值填充文本字段

ExampleViewController.m

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  // This needs to be the same value as used in the javascript
  NSString *bridgeScheme = @"myapp";

  // That's where we capture the request if the request's scheme matches
  if ([request.URL.scheme isEqualToString:bridgeScheme])
  {
    // Extract the part of the request url that contains the data we need
    NSString *dataString = [request.URL.absoluteString substringFromIndex:bridgeScheme.length + 1];
    // The data was URL encoded
    dataString = [dataString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    // Here we transform the JSON string into a JSON object (dictionary)
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    // Extract the field id from the dictionary
    NSString *fieldId = dataDictionary[@"field-id"];

    // Call the javascript method on the webview
    NSString *populateFieldJS = [NSString stringWithFormat:@"populateField('%@', '%@')", fieldId, @"Whatever text you want to put in there"];
    [webView stringByEvaluatingJavaScriptFromString:populateFieldJS];

    return NO;
  }

  return YES;
}

希望能帮助到你!

于 2013-05-24T01:35:30.603 回答