UITableViewCell With UIWebView Dynamic Height

前端 未结 10 2053
深忆病人
深忆病人 2020-12-04 11:52

I have a table view with cells that have a webView in them, I want the height of the cell to match the height of the webView.

This is the code I use:



        
10条回答
  •  粉色の甜心
    2020-12-04 12:01

    The most easy and elegant way is

    1. Add height layout constraint for webview
    2. Add webview Delegate finished loading then set contentSize height to constant of height layout constraint.

    3. Keep instance of tableview or make a delegate - block - closure to main tableview.

    4. Call tableview beginupdate endupdate to let tableview know they should validate layout.

    class WebViewTableViewCell: UITableViewCell {
        weak var viewController: ViewController? = nil
        @IBOutlet weak var webView: UIWebView!
        @IBOutlet weak var heightLayoutConstraint: NSLayoutConstraint!
        
        override func awakeFromNib() {
            super.awakeFromNib()
            webView.loadRequest(URLRequest(url: URL(string: "https://tinhte.vn")!))
            webView.delegate = self
            webView.scrollView.isScrollEnabled = false
            // Initialization code
        }
    
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
    
            // Configure the view for the selected state
        }
    
    }
    extension WebViewTableViewCell: UIWebViewDelegate {
        func webViewDidFinishLoad(_ webView: UIWebView) {
            heightLayoutConstraint.constant = webView.scrollView.contentSize.height
            viewController?.tableView.beginUpdates()
            viewController?.tableView.endUpdates()
        }
    }

提交回复
热议问题