加载后更改UITableViewCell高度

时间:2016-07-05 14:54:35

标签: ios swift uitableview autolayout

我在单元格内部有自定义UITableViewCell和UIWebView。 UIWebView具有默认高度约束(20像素)。

class TableViewCell: UITableViewCell, UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var webViewHeight: NSLayoutConstraint!

    func webViewDidFinishLoad(webView: UIWebView) {

       webView.frame.size.height = 1
       var contentSize = webView.scrollView.contentSize

       webView.frame.size.height = contentSize.height
       webView.scrollView.frame.size.height = contentSize.height

       webViewHeight.constant = contentSize.height

    }
}

然后我将我要加载的内容设置为webView。加载UIWebViewDelegate后调用webViewDidFinishLoad,然后更改高度约束。此时我在调试区域看到约束错误。

2016-07-06 09:11:20.492 TEST CELL[1746:56476] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. 
Try this: 
    (1) look at each constraint and try to figure out which you don't expect; 
    (2) find the code that added the unwanted constraint or constraints and fix it. 
 (
"<NSLayoutConstraint:0x7fbc087088f0 V:[UIWebView:0x7fbc0871eb70(50)]>",
"<NSLayoutConstraint:0x7fbc086b46f0 UIWebView:0x7fbc0871eb70.top == UITableViewCellContentView:0x7fbc0871dea0.topMargin>",
"<NSLayoutConstraint:0x7fbc086b4740 UITableViewCellContentView:0x7fbc0871dea0.bottomMargin == UIWebView:0x7fbc0871eb70.bottom>",
"<NSLayoutConstraint:0x7fbc08700c10 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7fbc0871dea0(59)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7fbc087088f0 V:[UIWebView:0x7fbc0871eb70(50)]>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

如何在加载后正确设置新的约束常量?

2 个答案:

答案 0 :(得分:1)

webViewDidFinishLoad可以多次调用,每次加载一帧时都必须检查此属性:

if (webview.isLoading) {
    return
} else {
    // do my stuff
}

答案 1 :(得分:0)

您可以通过将webView固定在TableViewCell上的约束的顶部和底部来实现此目的,然后在您的班级中使用UITableView显示此单元格,设置

tableView.rowHeight = UITableViewAutomaticDimension

使用webView中的约束设置TableViewCell func webViewDidFinishLoad的高度。

这将为单元格提供正确的高度,因此最后您可能需要使用某个委托模式来调用UITableView来重新加载(可能只是重新加载此单元格的indexPath)。