Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Final Layout Size for View with Flexible Width in UITableViewCell

I am using size classes in an iOS 8-only app and I have a view inside a UITableViewCell that has a flexible width. Its auto layout constraints are defined as follows:

enter image description here

As you can see, its width varies depending on the device width/orientation.

When I print its frame in cellForRowAtIndexPath I see (180.0, 10.0, 400.0, 60.0) which shows a 400 width. But when I measure the view in the simulator, it is only 175 wide, which is reinforced by the fact that my view's content is truncated (I'm drawing some stuff inside it).

How can I know when the UITableViewCell's contraints and subviews are completely done rendering so that I can redraw stuff inside my view?

Update

In cellForRowAtIndexPath I'm doing the following to get the cell:

let cell = tableView.dequeueReusableCellWithIdentifier("TimeTypeCell", forIndexPath: indexPath) as! TimeTypeCell

let customField = customFields[indexPath.row]

cell.fieldNameLabel.text = customField["name"] as? String
cell.fieldValueLabel.text = customField["total"] as? String
cell.graphData = customField["totalGraph"] as! [Double]

cell.fieldGraph.dataSource = cell.self
cell.fieldGraph.delegate = cell.self

cell.fieldGraph.reloadData() //This is where the redrawing happens
like image 788
Clifton Labrum Avatar asked May 14 '15 23:05

Clifton Labrum


2 Answers

Call cell.contentView.layoutIfNeeded() to get the content views laid out correctly. While the cell itself should be the correct size when returned from tableView.dequeueReusableCellWithIdentifier(_, forIndexPath:), it seems that the content view doesn't immediately run layout, so you need to call it manually if you need it up to date at that point.

like image 161
BJ Homer Avatar answered Nov 03 '22 21:11

BJ Homer


I ended up with overriding UITableViewCell.layoutSubviews method:

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.contentView layoutSubviews]; // this does the trick
}
like image 20
mixel Avatar answered Nov 03 '22 22:11

mixel