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.