How to Get UIWebView Content Size in Swift (WKWebView Too)

How to Get UIWebView Content Size in Swift (WKWebView Too)

Written by

in

Quick answer: UIWebView does not override sizeThatFits(:), so it returns the view’s current bounds instead of the page height. Shrink the frame height to 1, call sizeThatFits(πŸ™‚ again, and restore the frame β€” or read webView.scrollView.contentSize after the page finishes loading. On WKWebView, use scrollView.contentSize or evaluate document.documentElement.scrollHeight.

Why this happens

sizeThatFits(_:) has a default implementation on UIView that returns the size portion of the view’s bounds rectangle. Subclasses override it when they can compute a better size β€” UIImageView, for example, returns the size of the image it is displaying. UIWebView does not give you a useful override: it has no idea how tall the rendered document is until it has laid the page out inside a frame of a known width and height.

So when you call webView.sizeThatFits(CGSizeZero) on a web view that is currently 320Γ—480, you get 320Γ—480 back. The page content is irrelevant to the answer.

The real content size lives in the web view’s internal scroll view. UIWebView exposes it as webView.scrollView.contentSize (available since iOS 5), and that value is only correct after the document has loaded and been laid out.

One more thing before the code: UIWebView is deprecated and App Store submissions that reference it are rejected. If you are writing new code, jump to the WKWebView section β€” the same ideas apply, with a supported API.

How to fix it

1. Read the scroll view’s content size

The shortest path is to skip sizeThatFits(_:) entirely and ask the scroll view:

import UIKit

final class ArticleViewController: UIViewController, UIWebViewDelegate {
    @IBOutlet private weak var webView: UIWebView!

    func webViewDidFinishLoad(_ webView: UIWebView) {
        webView.scrollView.isScrollEnabled = false
        let contentHeight = webView.scrollView.contentSize.height
        print("content height: \(contentHeight)")
    }
}

This is the value you want in most cases. It is correct once webViewDidFinishLoad(_:) fires, but it can grow afterwards if the page loads images or web fonts that change the layout. If your HTML is remote, re-read it after a short delay or observe the scroll view’s contentSize with KVO.

2. Force a layout pass, then call sizeThatFits(_:)

If you need the fitting size rather than the scroll view’s cached value, the trick is to make the web view lay itself out at a tiny height first. With the frame collapsed, sizeThatFits(_:) has to compute a real answer instead of echoing the bounds:

func webViewDidFinishLoad(_ webView: UIWebView) {
    var frame = webView.frame
    frame.size.height = 1
    webView.frame = frame

    let fittingSize = webView.sizeThatFits(CGSize.zero)

    frame.size = fittingSize
    webView.frame = frame
}

Both frame assignments happen in the same run loop iteration, so the view is never displayed at the intermediate height and you will not see a flicker. This works on iOS 6 and later.

3. Pass the width you actually want

sizeThatFits(CGSizeZero) ignores its argument, which is why the previous approach depends on the frame already having the right width. A more explicit version sets the width yourself and passes it in, so the result is predictable even when the web view sits inside a UIScrollView alongside other content:

func webViewDidFinishLoad(_ webView: UIWebView) {
    let width = webView.bounds.width

    webView.scrollView.isScrollEnabled = false
    webView.frame.size = CGSize(width: width, height: 1)

    let fittingSize = webView.sizeThatFits(
        CGSize(width: width, height: .greatestFiniteMagnitude)
    )

    webView.frame.size = CGSize(width: width, height: fittingSize.height)
}

Because the width is fixed, the returned height is the height the document needs at that width β€” which is exactly what you need to size a parent container or a table cell.

4. Do the same thing with WKWebView

WKWebView has the same scroll view, so the first approach carries over unchanged:

import WebKit

final class ArticleViewController: UIViewController, WKNavigationDelegate {
    private let webView = WKWebView()

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.scrollView.isScrollEnabled = false
        let contentHeight = webView.scrollView.contentSize.height
        print("content height: \(contentHeight)")
    }
}

If contentSize looks stale, ask the DOM directly. This is the most reliable number because it comes from the rendered document:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.documentElement.scrollHeight") { result, error in
        guard let number = result as? NSNumber else { return }
        let height = CGFloat(number.doubleValue)
        print("document height: \(height)")
    }
}

document.body.scrollHeight and document.body.offsetHeight are alternatives if your markup puts the content in a body with unusual margins.

5. Use it from SwiftUI

Wrap the web view in a UIViewRepresentable and push the measured height back through a binding. Load the HTML in makeUIView β€” reloading it in updateUIView would trigger a new measurement, which updates the binding, which calls updateUIView again:

import SwiftUI
import WebKit

struct HTMLView: UIViewRepresentable {
    let html: String
    @Binding var height: CGFloat

    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        webView.scrollView.isScrollEnabled = false
        webView.loadHTMLString(html, baseURL: nil)
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {}

    func makeCoordinator() -> Coordinator { Coordinator(height: $height) }

    final class Coordinator: NSObject, WKNavigationDelegate {
        @Binding private var height: CGFloat

        init(height: Binding<CGFloat>) { _height = height }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            webView.evaluateJavaScript("document.documentElement.scrollHeight") { result, _ in
                guard let number = result as? NSNumber else { return }
                DispatchQueue.main.async {
                    self.height = CGFloat(number.doubleValue)
                }
            }
        }
    }
}

Then give the view a frame height of height in your layout.

How to prevent it

  • Never trust sizeThatFits(_:) on a web view whose frame is already the size you are asking about β€” collapse the height first or pass an explicit width.
  • Measure only after the load delegate fires; before that the document has no layout.
  • Turn off scrolling (webView.scrollView.isScrollEnabled = false) when you embed the web view in a parent scroll view, otherwise the inner scroll view swallows gestures.
  • Re-measure when the page can change after load (images, fonts, injected CSS) rather than caching the first height forever.
  • Use WKWebView for anything you intend to ship; UIWebView is deprecated and rejected at App Store review.

FAQ

Why does sizeThatFits return the same size as my frame?

Because UIWebView does not override the default UIView implementation, which returns the size portion of the view’s bounds. The web content plays no part in the calculation until you force a layout at a different height.

Is webView.scrollView.contentSize reliable?

It is reliable after the page finishes loading, and it is the simplest option. It can be stale if the document reflows later β€” for example when images finish downloading β€” so re-read it or observe it with KVO if your content is remote.

Can I use these approaches with WKWebView?

Yes. WKWebView exposes the same scrollView, so scrollView.contentSize works the same way, and evaluateJavaScript("document.documentElement.scrollHeight") gives you the rendered document height directly.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.