TableView Cell的高度不会根据WebView动态更改

时间:2019-03-11 10:06:30

标签: swift uitableview wkwebview

我在WKWebView单元格中使用了Tableview,它的height并没有根据webView中的内容而变化。

如果我直接在Webview中加载htmlString,则即使调用updateCellHeight(),单元格的高度也不会改变。

这是我的自定义单元(urlString来自API调用响应,因此每次都会不同):

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

     }

这是NewCatDescrDCell单元格:

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)
    }

}

如果我使用height来加载url内的内容,WebView会动态变化,但不适用于HTMLString

1 个答案:

答案 0 :(得分:0)

我在Stackoverflow上发现了与WKWebView高度有关的类似问题。

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
        })
    }

    })}

尝试此操作或在Stackoverflow上参考 How to determine the content size of a WKWebView?