-1

I have a table view with a few cells. The text that fills up the cell is unpredictable (based on the result of an API request). What I want to do is adjust the cell's height based on if the cell's text is too lengthy for the cell (e.g. the cell adds '...' to the text).

That way whatever the result/text and gets presented into a table view cell is always fully shown.

I would prefer not to implement the heightForRowAtIndexPath because I would have to implement a lot of code to do so.

UPDATE:

When I say "I have a lot of code to do so", I mean I literally have a lot of code parsing out requests and checking for conditions and performing algorithms and plus I have many table views. Just moved that stuff to another method and Im off to go!

Could you point me to any resources demoing this, do you know how to do this?

MCKapur
  • 9,127
  • 9
  • 58
  • 101
  • 3
    I don't think that there is an alternative. If you want a table view with varying cell heights, then you have to implement `heightForRowAtIndexPath`. – Martin R Oct 26 '12 at 12:10
  • 2
    How do you expect to have variable row height without `tableView:heightForRowAtIndexPath:`? What's wrong with implementing it - it's easy. – hoha Oct 26 '12 at 12:11

2 Answers2

3

You must implement heightForRowAtIndexPath to vary the height of your table rows, but there isn't necessarily alot of code needed to calculate the height.

Use NSString:sizeWithFont:constrainedToSize to calculate the cell size needed.

    //szMaxCell contains the width of your table cell, and the maximum height you want to allow
// strCellContents is an NSString containing the text to display

        CGSize szMaxCell = CGSizeMake (tableView.frame.size.width - 20,999);
        UIFont *font = [UIFont systemFontOfSize:12];    // whatever font you're using to display
        CGSize szCell = [strCellContents sizeWithFont:font constrainedToSize:szMaxCell lineBreakMode:UILineBreakModeWordWrap];

szCell contains the size of the label. You'll use this size both to calculate the frame of your UILabel in your cellForRowAtIndexPath, as well as in your heightForRowAtIndexPath.

CSmith
  • 13,318
  • 3
  • 39
  • 42
  • `sizeWithFont ` has been deprecated since iOS 7.0 and replaced with `boundingRectWithSize`. For an example see: http://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size – Ryan Epp Aug 23 '15 at 00:57
1

Use heightForRowAtIndexPath. It shouldn't be lots of extra code. Just get a reference to the object you are populating your cell with, check out the length of that text value and return the height you need. That is exactly what that delegate method is designed for.

LJ Wilson
  • 14,445
  • 5
  • 38
  • 62