When does a UITableView’s contentSize get set?

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

Leave a Comment