UITableView高度基于单元格数

Chr*_*n-G 13 objective-c uitableview ios

我有一个UITableView具有可变数量的行(单元格) - 这些行的高度是恒定的.我想要的是使UITableView的高度取决于行数.

另外,我希望UITableView正好包裹单元格,因此底部没有填充.因此,如果一个单元格的高度为60,则对于一个单元格,tableview应为60,对于两个单元格应为120,等等...

提前致谢!

Tim*_*len 28

您可以访问数据源以查找将显示的单元格数.将此数字乘以一行的高度,您将获得整个表格视图的高度.要更改表视图的高度,可以更改其frame属性.

您可以通过访问其rowHeight属性来访问表视图的一行的(常量)高度.如果myArray使用调用的数组的对象填充表视图,则可以使用以下代码:

CGFloat height = self.tableView.rowHeight;
height *= myArray.count;

CGRect tableFrame = self.tableView.frame;
tableFrame.size.height = height;
self.tableView.frame = tableFrame;
Run Code Online (Sandbox Code Playgroud)

您还可以通过询问表视图本身而不是数据对象来查找表视图将包含多少行.这样的事情应该有效:

NSInteger numberOfCells = 0;

//finding the number of cells in your table view by looping through its sections
for (NSInteger section = 0; section < [self numberOfSectionsInTableView:self.tableView]; section++)
    numberOfCells += [self tableView:self.tableView numberOfRowsInSection:section];

CGFloat height = numberOfCells * self.tableView.rowHeight;

CGRect tableFrame = self.tableView.frame;
tableFrame.size.height = height;
self.tableView.frame = tableFrame;

//then the tableView must be redrawn
[self.tableView setNeedsDisplay];
Run Code Online (Sandbox Code Playgroud)

  • 好吧,找到细胞数不是问题,计算高度也不是.事实是tableView框架的高度没有变化(这可能是因为我的代码存在于ViewDidLoad中? (4认同)