我在iOS 9上遇到了几个奇怪的wkWebView行为,我相信这两个问题是以某种方式连接的......
wkWebView
中的文字选择不起作用。作为测试环境,我将HTML文件加载到wkWebView
。成功加载后,我使用webkitColumnWidth
将文本分成列。执行此操作后,我可以看到使用长按不能选择文本的某些部分。例如,在其中一段(<p>
)中,可以选择部分文本,但文本的另一部分对长按没有反应。同时,我通常可以将我的选择扩展到长按不正常的文本区域。为什么会这样?有没有办法同时使用webkitColumnWidth
选择任何长文本?WKWebView
并手动选择一些带有长按的文本。执行此操作后,我希望显示内置菜单,但它不会......只有在已经选择的文本上单击第二次后才会显示。我的问题是:每次选择长按文本时,如何强制显示菜单?以下是我的代码段:
-(void)viewDidLoad{
NSString *javascript =[NSString stringWithFormat:@"var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=%f, height=%f, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);document.addEventListener(\"selectionchange\", function(){window.location = 'ios:';}, false);",rect.size.width,rect.size.height];
WKUserScript* userscr = [[WKUserScript alloc] initWithSource: javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[contentController addUserScript:userscr];
WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
config.userContentController = contentController;
WKWebView* webView = [[WKWebView alloc] initWithFrame:rect configuration:config];
webView.navigationDelegate = self;
…
NSString *htmlStr = [NSString stringWithContentsOfFile:htmlPath
encoding:NSUTF8StringEncoding
error:nil];
NSURL* baseURL = [[NSURL alloc] initFileURLWithPath:htmlPath];
[webView loadHTMLString:ch.html baseURL:baseURL];
}
- (void)webView:(WKWebView *)wView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
NSString * insertRule1 = [NSString stringWithFormat:@"document.getElementsByTagName('html')[0].style.webkitColumnWidth = '%fpx';document.getElementsByTagName('html')[0].style.height = '%fpx';document.getElementsByTagName('html')[0].style.width = '%fpx';document.getElementsByTagName('body')[0].style.marginRight = '10px';document.getElementsByTagName('body')[0].style.marginLeft = '10px';document.getElementsByTagName('html')[0].style.webkitColumnGap='0px';",self.view.frame.size.width/2-20,self.viewWV.frame.size.height,self.view.frame.size.width];
[wView evaluateJavaScript:[NSString stringWithFormat:insertRule1 completionHandler:nil];
}