6

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?

Luda
  • 7,282
  • 12
  • 79
  • 139

3 Answers3

3
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 {

                }
            })
        }
    })
}
NiTrOs
  • 359
  • 2
  • 7
0

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)
Luda
  • 7,282
  • 12
  • 79
  • 139
-4

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!

Community
  • 1
  • 1
maddy
  • 4,001
  • 8
  • 42
  • 65