Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different UITableViewCell heights

I have built three different cells in my storyboard and hooked all the outlets up, each cell has a unique identifier.

For example I have one cell which holds a picture, another which has a label and another with other contents, so they are all unique and each cell type requires its own height (dynamic or status, it doesn't matter).

However, how is it that I can make a cell with 'indentifier1' return a certain height and then the others cells returns different heights?

I know I can use - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath but I am unsure how to differentiate the cells.

I am using core data and fetch results for the tableview from that.

Edit

I have tried this with tags but its crashes at the first if statement:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellHeight;

    if ([[tableView cellForRowAtIndexPath:indexPath] tag] == 1) cellHeight = 170;
    else if ([[tableView cellForRowAtIndexPath:indexPath] tag] == 2) cellHeight = 100;
    else if ([[tableView cellForRowAtIndexPath:indexPath] tag] == 3) cellHeight = 140;

    return cellHeight;
}
like image 717
Josh Kahane Avatar asked Jun 28 '12 20:06

Josh Kahane


People also ask

How to increase height of cell in tableView in iOS 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. We'll see this with the help of an sample project.

How do you find the height of a cell?

On the Home tab, in the Cells group, click Format. Under Cell Size, click AutoFit Row Height. Tip: To quickly autofit all rows on the worksheet, click the Select All button, and then double-click the boundary below one of the row headings.


2 Answers

Updated

Use dynamic height of UITableView now as it's easy as UITableView automatically calculates it

Old

Use this method to your requirement below is an example:

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

  //calculate height according to text and on basis of indexPath
  if(indexpath.row == 0)
  {
    return 60.0f;
  }
  else if(indexpath.row == 1)
  {
    return 70.0f;
  }
  else
  {
    return 55.0f;
  }
}

Note : if your size is not fixed then you will have calculate it then provide in above method according to your requirement.

like image 155
Paresh Navadiya Avatar answered Sep 21 '22 11:09

Paresh Navadiya


You shouldn't call cellForRowAtIndexPath within heightForRowAtIndexPath or you'll enter an infinite loop which will cause the app crash.

You should determine the height of every cell in the same way you determine the type of the same cell in cellForRowAtIndexPath.

That's the only solution I think.

like image 37
Hejazi Avatar answered Sep 25 '22 11:09

Hejazi