Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

ios - When does a UITableView's contentSize get set?

I have a non scrolling UITableView in a UIScrollView. I set the frame size of the UITableView to its content size.

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;
}

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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;
}

Swift

override var preferredContentSize: CGSize {
    get {
        // Force the table view to calculate its height
        self.tableView.layoutIfNeeded()
        return self.tableView.contentSize
    }
    set {}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...