UITableViewCell subviews report incorrect width wh

2019-04-19 10:35发布

问题:

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

回答1:

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.



回答2:

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



回答3:

You can try in the method layoutSubviews(), after calling [cell layoutIfNeeded] to get "right" values for the subviews.