什么时候UITableView的contentSize被设置? [英] When does a UITableView's contentSize get set?
问题描述
我在 UIScrollView
中有一个非滚动的 UITableView
。我将 UITableView
的帧大小设置为其内容大小。
I have a non scrolling UITableView
in a UIScrollView
. I set the frame size of the UITableView
to its content size.
当我向<$添加一行时c $ c> UITableView ,我在 UITableView
上调用 insertRowsAtIndexPaths:withRowAnimation
:.然后我调用一个方法来调整 UITableView的框架
:
When I add a row to the UITableView
, I call insertRowsAtIndexPaths:withRowAnimation
: on the UITableView
. Then I call a method to resize the frame of the UITableView
:
- (void)resizeTableViewFrameHeight
{
// Table view does not scroll, so its frame height should be equal to its contentSize height
CGRect frame = self.tableView.frame;
frame.size = self.tableView.contentSize;
self.tableView.frame = frame;
}
似乎 contentSize
此时尚未更新。如果我根据行数和节数手动计算上述方法中的帧,那么方法就可以正常工作。
It seems though that the contentSize
hasn't been updated at this point. If I manually calculate the frame in the above method based on the number of rows and sections, then the method works properly.
我的问题是,我怎样才能得到 UITableView
更新其 contentSize
?我想我可以调用 reloadData
并且可能会这样做,但是当我只插入一个单元格时重新加载整个表似乎效率低。
My question is, how can I get the UITableView
to update its contentSize
? I suppose I could call reloadData
and that would probably do it, but it seems inefficient to reload the entire table when I'm just inserting one cell.
推荐答案
您可以通过在UITableView上调用 layoutIfNeeded
来强制UITableView计算内容的大小。
You can force the UITableView to calculate the size of the content by calling layoutIfNeeded
on the UITableView.
应该在容器视图中具有可变大小的UITableViewController子类的示例:
Example for a UITableViewController subclass that should be in a container view with variable size:
- (CGSize)preferredContentSize
{
// Force the table view to calculate its height
[self.tableView layoutIfNeeded];
return self.tableView.contentSize;
}
更新2016-07-28
这是一个未经测试的Swift同样的例子。它应该工作,但如果没有,请发表评论。可能有更好或更惯用的方法来做到这一点。不幸的是我对Swift不太熟悉。
Update 2016-07-28 This is an untested Swift example of the same thing. It should work but if it doesn't please leave a comment. There might be nicer or more idiomatic ways to do this. Unfortunately I am not very familiar with Swift.
override var preferredContentSize: CGSize {
get {
self.tableView.layoutIfNeeded()
return self.tableView.contentSize
}
set {}
}
这篇关于什么时候UITableView的contentSize被设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!