UIWebView dynamic content size

后端 未结 9 1615
北海茫月
北海茫月 2020-12-01 09:21

I\'ve been looking around and wasnt able to see any swift related ways to do this. I\'m trying to get my UIWebViews height to be dynamic. I have a UIWebView that loads data

9条回答
  •  醉梦人生
    2020-12-01 10:05

    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
    }
    

提交回复
热议问题