When does a UITableView#39;s contentSize get set?(UITableView 的 contentSize 何时设置?)
问题描述
我在 UIScrollView
中有一个非滚动 UITableView
.我将 UITableView
的帧大小设置为其内容大小.
I have a non scrolling UITableView
in a UIScrollView
. I set the frame size of the UITableView
to its content size.
当我向 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立即计算出内容的大小.这将运行所有必要的计算来布局 UITableView
.
You can make the UITableView calculate the size of the content immediately by calling layoutIfNeeded
on the UITableView
. This will run all the necessary calculations to layout the UITableView
.
UITableViewController
子类示例,您希望将其放入可变大小的容器视图中:
Example for a UITableViewController
subclass that you want to put in a container view with variable size:
Objective-C
- (CGSize)preferredContentSize
{
// Force the table view to calculate its height
[self.tableView layoutIfNeeded];
return self.tableView.contentSize;
}
斯威夫特
override var preferredContentSize: CGSize {
get {
// Force the table view to calculate its height
self.tableView.layoutIfNeeded()
return self.tableView.contentSize
}
set {}
}
这篇关于UITableView 的 contentSize 何时设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:UITableView 的 contentSize 何时设置?


- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01