問(wèn)題描述
我在 UIScrollView
中有一個(gè)非滾動(dòng) UITableView
.我將 UITableView
的幀大小設(shè)置為其內(nèi)容大小.
I have a non scrolling UITableView
in a UIScrollView
. I set the frame size of the UITableView
to its content size.
當(dāng)我向 UITableView
添加一行時(shí),我在 UITableView
上調(diào)用 insertRowsAtIndexPaths:withRowAnimation
:.然后我調(diào)用一個(gè)方法來(lái)調(diào)整 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;
}
目前看來(lái),contentSize
尚未更新.如果我在上述方法中根據(jù)行數(shù)和節(jié)數(shù)手動(dòng)計(jì)算框架,則該方法可以正常工作.
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.
我的問(wèn)題是,如何讓 UITableView
更新其 contentSize
?我想我可以調(diào)用 reloadData
并且可能會(huì)這樣做,但是當(dāng)我只插入一個(gè)單元格時(shí)重新加載整個(gè)表格似乎效率低下.
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
上調(diào)用layoutIfNeeded
可以讓UITableView立即計(jì)算出內(nèi)容的大小.這將運(yùn)行所有必要的計(jì)算來(lái)布局 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
子類(lèi)示例,您希望將其放入可變大小的容器視圖中:
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 {}
}
這篇關(guān)于UITableView 的 contentSize 何時(shí)設(shè)置?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!