使用UIWebView
带可编辑内容时,用户可以在可编辑的DIV上键入自己的文本.
有没有办法在每次用户更改可编辑文本时触发ViewController上的事件(类似于the UITextField
值更改事件)?
ViewController需要知道用户何时更改为文本有两个原因; 了解用户是否输入了任何文本,并在内容文本增长时调整UIWebView的大小.
该UIWebView
代表似乎并不包括这种类型的事件.这可能必须通过Javascript完成,但似乎无法找到答案.救命!
没有直接的方法来监听UIWebView中的事件,但您可以桥接它们.从iOS7开始,它很简单,因为有JavaScriptCore.framework(你需要将它与项目链接):
JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; ctx[@"myUpdateCallback"] = ^(JSValue *msg) { [self fieldUpdated]; }; [ctx evaluateScript:@"document.getElementById('myEditableDiv').addEventListener('input', myUpdateCallback, false);"];
(我目前无法测试代码,但我希望它有效)
在iOS7之前(如果你想支持更低版本,你必须使用它),这有点棘手.你可以在webView委托方法上监听webView:shouldStartLoadWithRequest:navigationType:
一些自定义方案,例如:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if ([request.URL.scheme isEqualToString:@"divupdated"]) { [self fieldUpdated]; return NO; } return YES; }
并在webView上触发这样的东西:
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('myEditableDiv').addEventListener('change', function () {" @"var frame = document.createElement('iframe');" @"frame.src = 'divupdated://something';" @"document.body.appendChild(frame);" @"setTimeout(function () { document.body.removeChild(frame); }, 0);" @"}, false);"];