0

I have tablewView cell with a maximum of three labels and two images. These labels and images do not always exist. How can I set my cell height according my existing labels and images?

This does not work:

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

 CGFloat h = kRowHeight;
FeedCell *cell = (FeedCell *)[tableView cellForRowAtIndexPath:indexPath];

if (!cell.cellTextLabel)
    h = 100.0;
return h;**
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Do you get an error like "Thread1: EXC_BAD_ACCESS" ? When I tried your code above, it got into a loop, that eventually gave me that error. – NickH Apr 06 '14 at 06:53

3 Answers3

0

From the docs, you'll want to implement the following method:

tableView:heightForRowAtIndexPath:
zadr
  • 2,505
  • 18
  • 19
0

When I used the code you provide to test, it got into a loop. It would set the kRowHeight to h, then it would try to call cellForRowAtIndexPath, and then repeat. Apparently, cellForRowAtIndexPath is run BEFORE cellForRowAtIndexPath. It is discussed in the top answer to this question Iphone - when to calculate heightForRowAtIndexPath for a tableView when each cell height is dynamic?

One way to determine the correct height is to check elsewhere about the reason to change the size. In that shared answer, they mention checking sizeWithFont if you have different fonts in the boxes.

In your case, you might be able to extract the part of your cellForRowAtIndexPath that determines whether the label is there or not, and then call that in your cellForRowAtIndexPath as well as here in heightForRowAtIndexPath. You extract it so you don't duplicate the code, and you just call it in two different places.

You may also have to run [self.tableView reloadData]. You maybe even have to call [self.view setNeedsLayout] (but this one I think is if you are updating it later, probably is not necessary in viewWillAppear).

Community
  • 1
  • 1
NickH
  • 683
  • 1
  • 5
  • 24
0

How do you remove the label on the cell? I ask because heigthForRow... Is called for each cell, so the if (!cell.label) statement will never be true, rigth?

I would add another custom cell without that label and set the heigthAtRow... According to each class of cell:

if([cell isKindOfClass [OneLabelCell class]]) {}

I hope it makes some sense.

Marcal
  • 1,371
  • 5
  • 19
  • 37