【发布时间】:2018-10-17 10:04:33
【问题描述】:
谁能告诉我我做错了什么?
我有一个 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
}
}
【问题讨论】:
-
您还没有做的一件事是将您的宽度和高度约束添加到任何东西(就代码显示而言)。您创建它们并将它们分配给变量,然后尝试激活它们,但是您实际上在哪里将它们添加到任何视图中。您可能需要将它们添加到 Web 视图中,并且可能还需要添加一些其他约束来确定其位置。
-
我在写这篇文章时做过 -> heightWebViewConstraint = NSLayoutConstraint(item: webView ....) 这个 webView 在 Xib 上的 StackView 设计中
-
所做的只是创建约束,它不会将其添加到任何视图中。你需要做类似
webView.addConstraint(heightWebViewConstraint的事情。 -
我会编辑我的代码,但这不起作用,并且单元格看起来像同一个 XD
-
嗯,这只是我对一个问题的最初想法,可能还有其他问题。首先,我建议使用您现在添加约束的方式更新代码。此外,堆栈视图设置如何以及单元设置其他部分的约束如何。还有你期待什么,因为它只有 1 点宽和 10 点高。
标签: ios swift uitableview uiwebview