Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

objective c - UITableView height based on number of cells

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.

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...

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...