Swift中WKWebView的使用与适配

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

    }

}

三、对比适配前后效果

   3.1、使用loadHTMLString(string, baseURL: nil)适配前如图1-1所示:


1-1

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


1-2
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

相关阅读更多精彩内容

友情链接更多精彩内容