UITableView高度基于单元格数 [英] UITableView height based on number of cells

查看:108
本文介绍了UITableView高度基于单元格数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a UITableView with a variable number of rows (cells) - the height of these rows is constant. What I would like is to make the height of the UITableView depend on the number of rows.

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

Also, I would like the UITableView to be exactly wrapping the cells, so no padding at the bottom. So if a cell has height 60, tableview should be 60 for one cell, 120 for two cells, etc...

提前致谢!

推荐答案

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

You could access your data source to find the number of cells that will be displayed. Multiply this number by the height of one row and you get the height of the entire table view. To change the height of a table view, you can change its frame property.

您可以通过访问它来访问表格视图中一行的(常量)高度code> rowHeight 属性。如果使用名为 myArray 的数组对象填充表视图,则可以使用以下代码:

You can access the (constant) height of one row of your table view by accessing its rowHeight property. If you fill your table view with the objects of an array called myArray, you could use the following code:

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

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

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

You could also find out how many rows the table view will contain by asking the table view itself, instead of the data object. Something like this should work:

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

这篇关于UITableView高度基于单元格数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆