Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set row height of a UITableView according to the cell in that row

I want to adjust the row height of a UITableView according to the cell in that row.

Initially, I tried to use

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

However, the problem is, when the table is loading, the calling flow is seemed to be:

First call:

(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

Then call:

(UIViewTableCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

which means, before my cell is generated, I have to tell the table the height of its row.

However, what I want is exactly the opposite, i.e., after my cell is generated, I tell the table the height of this rows.

Is there any method to achieve this?

like image 528
HanXu Avatar asked Nov 07 '13 12:11

HanXu


People also ask

How do I change cell height in Swift?

To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we'll need to make use of automatic dimension property.

How do you find the height of a cell?

Select the row or rows that you want to change. On the Home tab, in the Cells group, click Format. Under Cell Size, click Row Height. In the Row height box, type the value that you want, and then click OK.

How do I populate UITableView?

There are two main base ways to populate a tableview. The more popular is through Interface Building, using a prototype cell UI object. The other is strictly through code when you don't need a prototype cell from Interface Builder.


1 Answers

Make an array of heights for every row based on the data from tableView: cellForRowAtIndexPath: and in the tableView heightForRowAtIndexPath: just take the height value from that array.

Declare in your implementation file:

NSMutableArray *heights;

In viewDidLoad: initialise it:

heights = [NSMutableArray array];

In tableView: cellForRowAtIndexPath: set the height for each row:

[heights addObject:[NSNumber numberWithFloat:HEIGHT]];

And in the tableView heightForRowAtIndexPath: return required height:

return [heights objectAtIndex:indexPath.row];

This should work because tableView: cellForRowAtIndexPath: is called for every cell and then for every cell tableView heightForRowAtIndexPath: is called.

like image 117
JPetric Avatar answered Oct 21 '22 00:10

JPetric