WKWebView加载本地html遇到的坑与解决办法

2018-09-13  本文已影响0人  艾欧尼亚

1、字体变小解决办法

Swift
let headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>"
                
self.wkwebview.loadHTMLString(headerString.appending(html), baseURL: nil)
Objective-C
NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>";
[strongSelf.contentWebView loadHTMLString:[headerString stringByAppendingString:model.detail] baseURL:nil];

2、空格太大的解决办法

遇到iOS的空格比安卓大很多

// 去掉所有空格
html = htmlStr.replacingOccurrences(of: "&nbsp;", with: "").replacingOccurrences(of: "<br />&nbsp;", with: "")

当html中有表格且格子里是空的,与要加上空格

//给空表格中间加空格
html = html.replacingOccurrences(of: "<td></td>", with: "<td>&nbsp;</td>")

3、调整图片显示边距,视频边距,行间距,表格边距

//css
        let htmlString = String(format:"<style type=\"text/css\"> img{max-width: 100%% !important;width:100%% !important;height: auto;} video{max-width: 100%% !important;width:100%% !important;height: auto;object-fit: fill;}  iframe{max-width: 100%% !important;width:100%% !important;height: \((ScreenW - 40) * 1.4);} p{line-height:25px;text-align: justify;} table{table-layout: fixed;max-width: 100%% !important;width:100%% !important;height:auto !important;font-size:14px;} </style>%@",html)

4、设置html中视频播放时不进入全屏

//先设置WKWebViewConfiguration
let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
wkwebview = WKWebView(frame: .zero, configuration: configuration)

//调用js设置
//防止有多个视频
guard self.totalHtml.contains("<video") else {
     return
}
        
let arr = totalHtml.components(separatedBy: "<video")
        
for i in 0 ..< arr.count {
      //设置视频在webview 上播放
      let webkitPlaysinline = "document.getElementsByTagName('video')[\(i)].setAttribute('webkit-playsinline', true)"
        
       webView.evaluateJavaScript(webkitPlaysinline, completionHandler: { (data, error) in 
       printLog(message: data)
                
       })
       let x5Playsinline = "document.getElementsByTagName('video')[\(i)].setAttribute('x5-playsinline', true)"
        
       webView.evaluateJavaScript(x5Playsinline, completionHandler: { (data, error) in
       printLog(message: data)
       })
       let playsinline = "document.getElementsByTagName('video')[\(i)].setAttribute('playsinline', true)"
       webView.evaluateJavaScript(playsinline, completionHandler: { (data, error) in
       printLog(message: data)
      })
 }

上一篇下一篇

猜你喜欢

热点阅读