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

后端 未结 4 964
无人共我
无人共我 2021-02-01 19:20

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?

4条回答
  •  生来不讨喜
    2021-02-01 20:03

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

提交回复
热议问题