This post has been updated for Swift 5 & WKWebView
So this is a really great function you wrote there, OP!
Here is just a shorter, more elegant version of your code:
// make sure to declare the delegate when creating your webView (add UIWebViewDelegate to class declaration as well)
myWebView.delegate = self
func webViewDidFinishLoad(webView: UIWebView) {
webView.frame.size.height = 1
webView.frame.size = webView.sizeThatFits(CGSize.zero)
}
Migrating to WKWebView
1) import WebKit
2) make your ViewController
inherit from WKNavigationDelegate
3) hook up the WKWebView
’s delegate: webView.navigationDelegate = self
4) implement the following protocol function:
webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
After migrating from UIWebView
to WKWebView
, above approach doesn’t seem to work anymore.
What you can do instead, is change the line with webView.sizeThatFits(CGSize.zero)
to:
webView.frame.size = webView.scrollView.contentSize
The full code for WKWebView
would then be:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.frame.size.height = 1
webView.frame.size = webView.scrollView.contentSize
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…