UITableView content height

拜拜、爱过 提交于 2019-12-19 09:09:23

问题


I have a UITableView that is set to not enable scrolling, and it exists in a UIScrollView. I'm doing it this way as the design specs call for something that looks like a table view, (actually there are two of them side by side), and it would be much easier to implement tableviews rather than adding a whole bunch of buttons, (grouped table views).

Question is, I need to know how big to make the container view for the scrollview, so it scrolls the whole height of the table views. Once loaded, is there any way to find the height of a tableview? There is no contentView property like a scroll view, frame seems to be static, etc...

Any thoughts?


回答1:


Use

CGRect lastRowRect= [tableView rectForRowAtIndexPath:index_path_for_your_last_row];
CGFloat contentHeight = lastRowRect.origin.y + lastRowRect.size.height;

You can then use the contentHeight variable to set the contentSize for the scrollView.




回答2:


A more general solution that works for me:

CGFloat tableViewHeight(UITableView *tableView) {
    NSInteger lastSection = tableView.numberOfSections - 1;
    while (lastSection >= 0 && [tableView numberOfRowsInSection:lastSection] <= 0)
        lastSection--;
    if (lastSection < 0)
        return 0;
    CGRect lastFooterRect = [tableView rectForFooterInSection:lastSection];
    return lastFooterRect.origin.y + lastFooterRect.size.height;
}

In addition to Andrei's solution, it accounts for empty sections and section footers.




回答3:


UITableView is a subclass of UIScrollView, so it has a contentSize property that you should be able to use no problem:

CGFloat tableViewContentHeight = tableView.contentSize.height;
scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, tableViewContentHeight);

However, as several other SO questions have pointed out, when you make an update to a table view (like inserting a row), its contentSize doesn't appear to be updated immediately like it is for most other animated resizing in UIKit. In this case, you may need to resort to something like Michael Manner's answer. (Although I think it makes better sense implemented as a category on UITableView)




回答4:


You can run over the sections and use the rectForSection to calculate the total height (this included footer and header as well!). In swift I use the following extension on UITableView

extension UITableView {
    /**
     Calculates the total height of the tableView that is required if you ware to display all the sections, rows, footers, headers...
     */
    func contentHeight() -> CGFloat {
        var height = CGFloat(0)
        for sectionIndex in 0..<numberOfSections {
            height += rectForSection(sectionIndex).size.height
        }
        return height
    }

}


来源:https://stackoverflow.com/questions/7801074/uitableview-content-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!