Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of a UITableView's content view?

I would like to get the size of a UITableView's content view when the table is populated. Any suggestions on how to do this?

like image 779
David Avatar asked Jul 28 '11 14:07

David


3 Answers

// Allows you to perform layout before the drawing cycle happens. 
//-layoutIfNeeded forces layout early. So it will correctly return the size. 
// Like dreaming before doing.

[tableView layoutIfNeeded];


CGSize tableViewSize=tableView.contentSize;
like image 92
Vijay-Apple-Dev.blogspot.com Avatar answered Nov 07 '22 16:11

Vijay-Apple-Dev.blogspot.com


Here's a utility method that does it the hard way. The negligible advantage is there's no need to call [tableView layoutIfNeeded].

#define CGSizesMaxWidth(sz1, sz2)             MAX((sz1).width, (sz2).width)
#define CGSizesAddHeights(sz1, sz2)           (sz1).height + (sz2).height

+ (CGSize)sizeForTableView:(UITableView *)tableView {
    CGSize tableViewSize = CGSizeMake(0, 0);
    NSInteger numberOfSections = [tableView numberOfSections];
    for (NSInteger section = 0; section < numberOfSections; section++) {
        // Factor in the size of the section header
        CGRect rect = [tableView rectForHeaderInSection:section];
        tableViewSize = CGSizeMake(CGSizesMaxWidth(tableViewSize, rect.size), CGSizesAddHeights(tableViewSize, rect.size));

        // Factor in the size of the section
        rect = [tableView rectForSection:section];
        tableViewSize = CGSizeMake(CGSizesMaxWidth(tableViewSize, rect.size), CGSizesAddHeights(tableViewSize, rect.size));

        // Factor in the size of the footer
        rect = [tableView rectForFooterInSection:section];
        tableViewSize = CGSizeMake(CGSizesMaxWidth(tableViewSize, rect.size), CGSizesAddHeights(tableViewSize, rect.size));
    }
    return tableViewSize;
}
like image 5
lambmj Avatar answered Nov 07 '22 15:11

lambmj


For table views whose heights are dynamically sized by their cells' contents--

My tableView is contained in a UIView, whose updateConstraints() function looks like this:

override func updateConstraints() {
    self.tableView.layoutIfNeeded()
    self.tableViewHeight.constant = min(300, self.tableView.contentSize.height)
    super.updateConstraints()
}

tableViewHeight is an IBOutlet to the XIB-assigned height of the table view. I get whichever is smaller--300 points, or the height of the table view's content size.

like image 5
MLQ Avatar answered Nov 07 '22 16:11

MLQ