我有一个设置为不启用滚动的UITableView,它存在于UIScrollView中。我这样做是因为设计规范要求看起来像桌面视图的东西(实际上它们中有两个并排),并且实现tableviews而不是添加一大堆按钮要容易得多,(分组表视图)。
问题是,我需要知道为scrollview创建容器视图的大小,因此它会滚动表视图的整个高度。一旦加载,有没有办法找到tableview的高度?没有像滚动视图那样的contentView属性,框架似乎是静态的等等......
有什么想法吗?
答案 0 :(得分:13)
使用
CGRect lastRowRect= [tableView rectForRowAtIndexPath:index_path_for_your_last_row];
CGFloat contentHeight = lastRowRect.origin.y + lastRowRect.size.height;
然后,您可以使用contentHeight变量为scrollView设置contentSize。
答案 1 :(得分:3)
对我有用的更通用的解决方案:
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;
}
除了安德烈的解决方案,它还会考虑空白部分和部分页脚。
答案 2 :(得分:1)
UITableView
是UIScrollView
的子类,因此它具有contentSize
属性,您应该可以毫无问题地使用它:
CGFloat tableViewContentHeight = tableView.contentSize.height;
scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, tableViewContentHeight);
但是,正如several other所提出的问题,当您对表格视图进行更新(例如插入行)时,其contentSize
不会出现像UIKit中大多数其他动画调整大小一样立即更新。在这种情况下,您可能需要诉诸Michael Manner的答案。 (虽然我认为更好地将其作为UITableView
)
答案 3 :(得分:1)
您可以遍历各个部分并使用rectForSection
来计算总高度(包括页脚和标题!)。在swift中,我在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
}
}