Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell subviews report incorrect width when using size classes

For some reason, when using size classes in xcode 6, I am getting incorrect widths for subviews in my cell. I have a UIImageView with autolayout for sizing (constant: 10 for top, L/R, bottom).

When calling the following from tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!):

println("w: \(cell.mapSnapshotImageView.bounds.size.width) h: \(cell.mapSnapshotImageView.bounds.size.height)")

I always get:

w: 580.0 h: 80.0

Even though it should be w: 300.0 h: 80.0 based on my 320x100 cell on an iPhone 5S.

Everything displays correctly, but I want to use the width of the subview for some calculations for other subviews. Any ideas as to why this is happening? Bug report or working as designed?

EDIT:

This issue only applies to cells that are loaded initially. When cells are reused, the issue does not present itself. println output on reused cells:

w: 300.0 h: 80.0
like image 472
Andrew Robinson Avatar asked Aug 28 '14 23:08

Andrew Robinson


2 Answers

Call cell.layoutIfNeeded() in willDisplayCell:forRowAtIndexPath before accessing the frames. That will do the trick.

like image 79
benkraus Avatar answered Sep 28 '22 00:09

benkraus


I also ran into this issue. When you dynamically change the size of the views the subviews need to update their values accordingly. You are referencing the values before they have been updated.

My work around was to reference the values after they had been updated. In this case it was in viewDidAppear(). Hope this provides some use. I spent a while trying to figure it out.

like image 43
running-codebase Avatar answered Sep 27 '22 23:09

running-codebase