1

I have used a WKWebView inside a Tableview cell, its height is not changing according to content inside webView.

If I directly load an htmlString inside webview, the height of the cell doesn't change even after calling updateCellHeight().

This is my Custom Cell (the urlString is coming from an API call response so each time it will be different):

let cell1: NewCatDescrDCell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath) as! NewCatDescrDCell
  if !loaded { 
                cell1.urlString = "<p>Headers and Builders</p>"
                cell1.configure()
                cell1.tableView = tableView
             }

        loaded = true
        return cell1

     }

This is NewCatDescrDCell cell:

class NewCatDescrDCell: UITableViewCell, WKNavigationDelegate {

let webView = WKWebView()
var tableView: UITableView!
var heights : CGFloat = 1200.0
var heightconstraint: NSLayoutConstraint!

var urlString: String = ""

override func awakeFromNib() {
    super.awakeFromNib()

    webView.translatesAutoresizingMaskIntoConstraints = false

    contentView.addSubview(webView)

    webView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    webView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
    webView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
    webView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
    webView.allowsBackForwardNavigationGestures = true


   }


func configure() {

    webView.navigationDelegate = self
    webView.scrollView.isScrollEnabled = true    
    webView.loadHTMLString(urlString, baseURL: nil)    

    }

 @objc func updateCellHeight() {
    heights = webView.scrollView.contentSize.height

    heightconstraint = webView.heightAnchor.constraint(equalToConstant: heights)
    heightconstraint.isActive = true

    tableView.reloadData()
    }

 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(updateCellHeight), userInfo: nil, repeats: false)
    }

}

The height changes dynamically if I use an url to load inside WebView, but it is not working for HTMLString.

denis_lor
  • 6,212
  • 4
  • 31
  • 55

1 Answers1

0

I found a similar issue related to the WKWebView height on Stackoverflow.

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
    if complete != nil {
        self.webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
            self.containerHeight.constant = height as! CGFloat
        })
    }

    })}

try this or refer this on Stackoverflow How to determine the content size of a WKWebView?

Joseph
  • 99
  • 12