我有UIWebView
并已从服务器加载了文档。 Web文档有几个文本输入字段。如何确定用户触摸的字段的ID或名称 - 已选中。然后我想分配一个值来填充输入字段。
我已经读过足以相信我需要JavaScript但不知道如何将它与Xcode中的目标c相关联。任何帮助将不胜感激。
由于 罗恩
答案 0 :(得分:0)
以下是一个简单实现的快速示例,可以帮助您入门。
<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函数,以使用您想要的任何值填充文本字段- (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;
}
希望它有所帮助!