在UITableViewCell内渲染UIWebView

时间:2018-10-17 10:04:33

标签: ios swift uitableview uiwebview

有人可以告诉我我在做什么错吗?

我有一个tableCell,里面有一个stackView,并有一个以编程方式添加的UIWebview。

class ChatTableViewCell: UITableViewCell {

  @IBOutlet var stackView: UIStackView!
  func setupCell(message: ChatMessage) {

        addHtmlToView(msg: "<p>This is <b>bold text</b></p>")
    }

 func addHtmlToView(msg: String) {
         let webView = UIWebView()
        webView.loadHTMLString("<html><body><div id='mainHtml'>" + msg + "</div></body></html>", baseURL: nil)
        webView.backgroundColor = UIColor.clear
        webView.isOpaque = false
        webView.delegate = self
        webView.scrollView.isScrollEnabled = false
        webView.scrollView.bounces = false
        webView.backgroundColor = .red
        webView.scrollView.contentInset = UIEdgeInsets(top: -8, left: -8, bottom: -8, right: -8)
        webView.translatesAutoresizingMaskIntoConstraints = false

        self.stackView.addArrangedSubview(webView)

        heightWebViewConstraint = NSLayoutConstraint(item: webView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 10)
        widthWebViewConstraint = NSLayoutConstraint(item: webView, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 1)

         webView.addConstraint(heightWebViewConstraint)
         webView.addConstraint(widthWebViewConstraint)

        NSLayoutConstraint.activate([ heightWebViewConstraint, widthWebViewConstraint])

    }
}

extension ChatTableViewCell: UIWebViewDelegate {

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
       if navigationType == UIWebView.NavigationType.linkClicked {
        UIApplication.shared.openURL(request.url!)
        return false
    }
    return true
}

func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.frame.size.height = 1.0        
    webView.sizeToFit()

    let result = NumberFormatter().number(from: webView.stringByEvaluatingJavaScript(from: "document.getElementById('mainHtml').offsetHeight") ?? "0")

    heightWebViewConstraint.constant = 200        
}

}

此后,单元格将呈现为enter image description here 接下来,我将使用“结果”中的值,但这也不适用于硬编码的值

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为您必须将“堆栈视图”的“分布”属性添加为“均等填充”

enter image description here