Swift中WKWebView的使用與適配

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

? ? }

}

三、對比適配前后效果

? ?3.1、使用loadHTMLString(string, baseURL: nil)適配前如圖1-1所示:


1-1

? 3.2、使用loadHTMLString(filterMethod(urlStr: string), baseURL: nil)適配后如圖1-2所示:


1-2
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容