Swift使用WKWebView加載并適配網(wǎng)頁
一喉脖、使用閉包獲取加載出來的網(wǎng)頁高度
注意:為防止內(nèi)存泄漏艺挪,使用weakself引用祖驱,退出時(shí)會(huì)來到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加載網(wǎng)頁的完整代碼如下(可根據(jù)自身需求添加到指定的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{
? ? ? ? ? ? ? ? //返回加載出來的網(wǎng)頁高度
? ? ? ? ? ? ? ? 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
? ? }
}