直接上码了 ,难度不大!
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.body.offsetHeight;") { (result, error) in
var frame:CGRect = webView.frame
frame.size.height = result as! CGFloat
frame.size.height += self.webViewHeaderView.frame.size.height //顶部
frame.size.height += self.webViewFooterView.frame.size.height //底部
webView.frame = frame
self.webView.scrollView.addSubview(self.webViewFooterView) // webView的内容加载完毕后再加载webViewFooterView
self.webViewFooterView.frame =
CGRect(x: 0,
y: webView.frame.maxY-self.webViewHeaderView.frame.size.height-self.webViewFooterView.frame.size.height,
width: screenWidth,
height: CGFloat(self.webFooterHeight))
self.tableView.tableHeaderView = webView
}
// MARK: - 取得HTML内所有的图片
let getImagesStr = "function getImages(){var objs = document.getElementsByTagName(\"img\");var imgSrc = '';for(var i=0;i<objs.length;i++){imgSrc=imgSrc + objs[i].src + '+';};return imgSrc;}"
webView.evaluateJavaScript(getImagesStr, completionHandler: nil)
webView.evaluateJavaScript("getImages()") { (result, error) in
//printLog((result as! String).components(separatedBy: "+"))
self.imgSrcArray = (result as! NSString).components(separatedBy: "+")
//printLog(self.imgSrcArray)
}
var getImageClick = "function registerImageClickAction(){"
getImageClick += " var imgs=document.getElementsByTagName('img');"
getImageClick += " var length=imgs.length;"
getImageClick += " for(var i=0;i<length;i++){"
getImageClick += " img=imgs[i];"
getImageClick += " img.onclick=function(){"
getImageClick += " window.location.href='img-preview:'+this.src}"
getImageClick += " }"
getImageClick += " }"
webView.evaluateJavaScript(getImageClick, completionHandler: nil)
webView.evaluateJavaScript("registerImageClickAction()") { (result, error) in
//print(result)
}
//didFinish WKWebview 禁止长按
webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';")
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let requestString = navigationAction.request.url?.absoluteString
if (requestString?.hasPrefix("img-preview:"))!{
let imageUrl: String? = requestString?.substring(from: ("img-preview:").endIndex)
printLog(imageUrl)
let nextVC = ImageDetailController()
nextVC.imageUrl = imageUrl!
navigationController?.pushViewController(nextVC, animated: true)
}
decisionHandler(WKNavigationActionPolicy.allow)
}
}
网友评论