[iOS] UIWebView with wrap content height

This is the solution of having UIWebView with wrap content height in iOS.

First bind your UIWebView and its height constraint. Implement the class with UIWebViewDelegate.

We can setup the UIWebView in awakeFromNib() if it is not in a View Controller.

// Setup webview
bodyWebView.backgroundColor = UIColor.clearColor()
bodyWebView.opaque = false
bodyWebView.delegate = self
bodyWebView.scrollView.scrollEnabled = false
bodyWebView.scrollView.bounces = false

Load the HTML content.

bodyWebView.loadHTMLString(bodyString, baseURL: nil)

Implement the UIWebViewDelegate.

func webViewDidFinishLoad(webView: UIWebView) {
    let result = bodyWebView.stringByEvaluatingJavaScriptFromString("document.body.offsetHeight;")
    if let n = NSNumberFormatter().numberFromString(result!) {
        let f = CGFloat(n) + 20/*margin*/
        if (bodyWebViewHeightConstraint.constant != f) {
            bodyWebViewHeightConstraint.constant = f
            
            dispatch_async(dispatch_get_main_queue(), {
                self.tableView().beginUpdates()
                self.tableView().endUpdates()
            })
        }
    }
}