Set a UIWebView’s height to the height of its HTML content using Auto Layout
Posted: | Author: Jörn | Filed under: iOS, Swift | Tags: Auto Layout, UIWebView | 11 Comments »In a previous post I described how to programmatically set the height of a UIWebView to fit the height of its HTML content.
This is a different approach using a Storyboard (and a little code). To make things a little bit more interesting I added an UIView that sits on top of the UIWebView and that should scroll out of view when the user scrolls the UIWebView. To make that happen we need an UIScrollView that contains the UIView and the UIWebView:
The UIView could be something like an iAd that you want to display on top of the web content but that should be scrolled out of the view when the user scrolls the web content.
Here is how to make it work:
- Connect the UIWebView from the nib to an outlet in your view controller.
- Disable scrolling in the UIWebView.
- Set the constraints on the `UIScrollView`, the `UIView` and the `UIWebView`:
- The UIScrollView needs a top, a bottom, a leading and a trailing constraint to the UIViewController’s view.
- The UIView needs a top, a leading and a trailing constraint to the UIScrollView. It also needs a width constraint that is equal to the UIScrollView’s width to avoid horizontal scrolling (See this post for an explaination). I also add a height constraint, because I want to have the UIView to have a constant height of 100pt.
- The UIWebView needs a top constraint to the UIView’s bottom, a leading, a trailing and a bottom constraint to the UIScrollview. It also needs a height constraint that we will later set to the height of the HTML content
- Connect the UIWebView‘s height constraint to an outlet in your view controller.
- Set the view controller as UIWebViewDelegate.
- In webViewDidFinishLoad set the height constraint’s constant to the height of the contentSize of the scroll view inside the web view.
- Start Key-Value Observing on the contentSize to change the height, when height of the web view has to change because segments of the webpage change their size without reloading the page (like accordeons, or menus). Don’t forget to stop observing when the view controller gets deallocated.
The constraints should look like this:
Here is the code that you need:
import UIKit
var MyObservationContext = 0
class ViewController: UIViewController {
@IBOutlet weak var webview: UIWebView!
@IBOutlet weak var webviewHeightConstraint: NSLayoutConstraint!
var observing = false
override func viewDidLoad() {
super.viewDidLoad()
webview.scrollView.isScrollEnabled = false
webview.delegate = self
if let url = URL(string: "https://www.google.de/intl/de/policies/terms/regional.html") {
webview.loadRequest(URLRequest(url: url))
}
}
deinit {
stopObservingHeight()
}
func startObservingHeight() {
let options = NSKeyValueObservingOptions([.new])
webview.scrollView.addObserver(self, forKeyPath: "contentSize", options: options, context: &MyObservationContext)
observing = true;
}
func stopObservingHeight() {
webview.scrollView.removeObserver(self, forKeyPath: "contentSize", context: &MyObservationContext)
observing = false
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else {
super.observeValue(forKeyPath: nil, of: object, change: change, context: context)
return
}
switch keyPath {
case "contentSize":
if context == &MyObservationContext {
webviewHeightConstraint.constant = webview.scrollView.contentSize.height
}
default:
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
extension ViewController: UIWebViewDelegate {
func webViewDidFinishLoad(_ webView: UIWebView) {
webviewHeightConstraint.constant = webview.scrollView.contentSize.height
if (!observing) {
startObservingHeight()
}
}
}
In case you have difficulties implementing this, i put a working example on github
EDIT
GitHub user kenji21 implemented this cool UIWebView subclass that get’s the job done with less code:
class ContentFittingWebView: UIWebView {
var contentSizeObservationToken: NSKeyValueObservation?
override func awakeFromNib() {
super.awakeFromNib()
startObservingHeight()
}
override var intrinsicContentSize: CGSize {
return scrollView.contentSize
}
func startObservingHeight() {
contentSizeObservationToken?.invalidate()
contentSizeObservationToken = scrollView.observe(\UIScrollView.contentSize, options: [.new], changeHandler: { (scrollView, change) in
self.invalidateIntrinsicContentSize()
})
}
}