swift之与h5之间的交互(一)

相信很多小伙伴会遇到这种问题,就是一个商品的售卖的页面下会有一个未知高度的图文介绍,今天就浅谈一下这个功能:

 

整个页面以一个tableView进行实现,图文详情这块主要是拿到后台给到的html进行渲染,然后根据渲染后的页面高度再做适配(h5页面适配手机)

主体思路:

1.在tableViewFootView里搭建好视图以及webview

wkWebView = WKWebView()
wkWebView.navigationDelegate = self
wkWebView.uiDelegate = self
wkWebView.scrollView.showsVerticalScrollIndicator = false
wkWebView.scrollView.bounces = false
wkWebView.scrollView.isScrollEnabled = false
//这里的footBackView是嵌套了一层=>方便外界直接修改footView的高度
footBackView.addSubview(wkWebView)
//wkWebView布局的代码用的是snapkit这里不在详情赘述 

2.渲染页面进行适配

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
    }
//以上这个方法主要作用是根据html的内容适配好各类手机宽高(model.introduction表示后台给的html数据)
self.wkWebView.loadHTMLString(self.filterMethod(urlStr: model.introduction ?? ""), baseURL: nil)

3.高度计算并刷新footView,在wkwebView代理方法里拿到高度并重新计算整个tabView的高度

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    var webheight = 0.0
    // 获取内容实际高度
    webView.evaluateJavaScript("document.body.scrollHeight") { [unowned self] (result, error) in
      if let tempHeight: Double = result as? Double {
        webheight = tempHeight//这里是获取到内容高度
      }
          //延迟更新高度
          DispatchQueue.main.async { [unowned self] in
                //这里可以更新tableViewfootView的高度,这个时候只需要改变footBackView的高度,然后重新给tableViewfootView赋值,xib的话可以通过
footView.systemLayoutSizeFitting(CGSize(width: pagingView.width, height: CGFloat.greatestFiniteMagnitude), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)的方式进行高度适配
} } }
posted @ 2024-03-07 10:17  哇哈爽  阅读(53)  评论(0编辑  收藏  举报