Artem Krachulov
Artem Krachulov

Reputation: 597

Change UITableViewCell height after loading

I have custom UITableViewCell with UIWebView inside cell. UIWebView have default height constraint (20 px).

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

    }
}

Then I set what I want to load into webView. After loading UIWebViewDelegate call webViewDidFinishLoad , and I change height constraint. And at this moment I see constraints error in debug area.

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.

How I can set properly new constraint constant after loading?

Upvotes: 2

Views: 866

Answers (2)

Sajjon
Sajjon

Reputation: 9897

You can achieve this by pinning webView to top and bottom with constraints in TableViewCell and then in your class with the UITableView this cell is displayed in, set

tableView.rowHeight = UITableViewAutomaticDimension

And setting the height of the webView in TableViewCell as you are doing with constraint in func webViewDidFinishLoad.

This will give the cell the correct height so lastly you might want to use some delegate pattern to call the UITableView to reload (maybe just reload the indexPath for this cell).

Upvotes: 0

Alessandro Ornano
Alessandro Ornano

Reputation: 35392

webViewDidFinishLoad can be called many times, every time a frame is done loading so you must check this property:

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

Upvotes: 1

Related Questions