Swift使用WKWebView加载并适配网页
一、使用闭包获取加载出来的网页高度
注意:为防止内存泄漏,使用weakself引用,退出时会来到deinit(销毁)
weak var weakself = self
cell.returnWebHeightBlock = { webHeight in
if let temh = weakself?.webcellh, temh>0{
return
}
weakself?.webcellh = webHeight
weakself?.reloadRows(at: [IndexPath.init(row:2,section:0)],with: .none)
}
deinit {
print("detailview deinit")
}
二、使用WKWebView加载网页的完整代码如下(可根据自身需求添加到指定的cell上):
import UIKit
import WebKit
class GJPublicWebView: WKWebView,WKNavigationDelegate {
typealias getWebViewH = (CGFloat)->()
var returnWebHeightBlock : getWebViewH?
override init(frame: CGRect, configuration: WKWebViewConfiguration?) {
super.init(frame: frame,configuration:WKWebViewConfiguration())
navigationDelegate = self
}
required init?(coder:NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func loadPublicWebHTMLString(_ string : String) {
loadHTMLString(filterMethod(urlStr: string),baseURL:nil)
}
func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.body.scrollHeight") { (result, err) in
if let temh = result as? CGFloat{
//返回加载出来的网页高度
self.returnWebHeightBlock?(temh)
}
}
}
//适配具体代码如下
private func filterMethod(urlStr:String) -> String {
let headHtml = NSMutableString.init(capacity:0)
headHtml.append("<html>")
headHtml.append("<head>")
headHtml.append("<meta charset=\"utf-8\">")
headHtml.append("<meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=false\" />")
headHtml.append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />")
headHtml.append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />")
headHtml.append("<meta name=\"black\" name=\"apple-mobile-web-app-status-bar-style\" />")
headHtml.append("<style>img{max-width:100%;width:auto;height:auto}</style>")
var bodyStr : String = String(headHtml)
bodyStr.append(urlStr)
return bodyStr
}
deinit{
navigationDelegate = nil
}
}