0

I have a table set up that displays some JSON data from the web. I have different types of elements in my data represented in different cells. Basically, I didn't subclass for every cell type, but I rather do a switch/case statement in the setObject/layoutSubviews/rowHeightForObject/etc methods. Now my problem is that certain cells contain a UILabel that varies based on the size of the text. What I do now, is create a label every time in the rowHeightForObject method and calculate it's size, to determine the height for that particular cell. Is there a more efficient way to do this?

Joris Weimar
  • 4,783
  • 4
  • 33
  • 53
  • Check out http://stackoverflow.com/questions/446405/adjust-uilabel-height-depending-on-the-text/447065#447065 for how to get the size without instantiating a UILabel. – Jeremy Flores Aug 14 '11 at 05:57

1 Answers1

0

You can use the TTStyledTextTableCell cell. There's a good example of it in the TTTwitter example project. the TTStyledTextTableCell accept a cell item with TTStyledText and adjust the height of the cell automatically.

If you're using a custom cell class, you will have to add a height function in your cell class and use TTStyledText instead of UILabel.

///////////////////////////////////////////////////////////////////////////////////////////////////
+ (CGFloat)tableView:(UITableView*)tableView rowHeightForObject:(id)object {
  TTStyledText* text = object;
  if (!text.font) {
    text.font = TTSTYLEVAR(font);
  }
  text.width = tableView.width - [tableView tableCellMargin]*2;
  return text.height;
}

The function calculates the height of TTStyledText class for each cell in the table data source.

aporat
  • 5,922
  • 5
  • 32
  • 54