UITableViewCell frame height not matching tableView:heightForRowAtIndexPath:

↘锁芯ラ 提交于 2019-11-29 14:14:53

As suggested by Flexo, answering this myself is apparently better than adding an edit to the question. So, here's the previous edit as an answer:


Nevermind, I should read the docs better. I can get the correct frame in the tableView:willDisplayCell:forRowAtIndexPath: method of UITableViewDelegate, so that is the correct place to do subview customization that relies on the correct frame being set, not cellForRowAtIndexPath:.

Interesting that the docs say this, though:

After the delegate returns, the table view sets only the alpha and frame properties, and then only when animating rows as they slide in or out.

...since the correct frame is already there when this delegate method is called. But anyway, problem solved.

Don't forget that the cell is a UIView, so overriding layoutSubviews is also a valid way to get the correct frame and adjust size/position of subviews. Just don't forget to call [super layoutSubviews].

Easiest way I found was just to call cell.layoutIfNeeded() before you do any setup on the cell. This makes sure all the layout constraints are calculated and the frames are set.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!