简体   繁体   中英

WKWebView not resizing when content changing

WKWebView is not resizing when content changing.

Here is a code snippet:

@IBOutlet weak var containingView: UIView!
var webView: WKWebView! 

override func viewDidLoad()
{
    super.viewDidLoad()

    let contentController = WKUserContentController();
    self.webView = WKWebView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height), configuration: WKWebViewConfiguration())
    self.webView.autoresizingMask = [.FlexibleHeight]
    self.webView.loadHTMLString(__, baseURL: __))
    self.webView.scrollView.bounces = false
    self.webView.scrollView.scrollEnabled = false

    self.containingView.addSubview(self.webView)
}

What func should be added so I could intercept content size being changed and change the containingView size accordingly?

What halped me was to have small initial WKWebView height

webView = WKWebView(frame: CGRectMake(0, 0, self.view.frame.width, 150), configuration: configuration)

instead of

webView = WKWebView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height), configuration: configuration)
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("webview did enter did finish navigation")
    webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
        if complete != nil {
            webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (result, error) in
                if let heightOfContent = result as? CGFloat {

                }
            })
        }
    })
}

Conceptually in objective c you should do like below.

Two things: Make sure to have these properties:

self.webView.scalesPageToFit = YES;
self.webView.contentMode = UIViewContentModeScaleAspectFit;

And finally calculate webView content height as :- webView.isLoading is one of the most important property. Actually in a single call to a web url it is called multiple times.

- (void)webViewDidFinishLoad:(UIWebView *)webView{
if (webView.isLoading == NO)// as it is called multiple times so wait untill last call
{
 CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.height"] floatValue];
}

}

This is how you should compute web view height.

you can have a look here as WKWebView don't have a delete which you can use to get content size instead use KVO:

KVO example May be it will help you more!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM