6

I'm trying to create a UITableViewCell that contains a UITextView and when the user enters text into the textview the cell should grow accordingly. This also works quite well so far, except that the boundingRectWithSize method ignores trailing line breaks when calculating the new cell size. This is what my method call looks like:

  CGRect rect = [text boundingRectWithSize:CGSizeMake(self.cellSize.width, CGFLOAT_MAX)
                                   options:NSStringDrawingUsesLineFragmentOrigin
                                attributes:@{NSFontAttributeName:[UIFont fontWithName:@"AvenirNext-Medium" size:14.0]}
                                   context:nil];

If I for example enter

Test
\n
\n

(line breaks visualised as "\n"), the method returns the size for a textview containing two lines and not three. I tried several options and als attributes but couldn't find a solution that works. How can I do this in a functioning way?

Lukas Spieß
  • 2,478
  • 2
  • 19
  • 24
  • You would probably be better off trying to use Auto Layout to automatically size your cells. See [this post](http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights). – ravron Jul 22 '14 at 15:45
  • Oh wow, that looks really interesting. Can't believe I've never seen it before. Thanks! – Lukas Spieß Jul 22 '14 at 17:06
  • Autolayout will not help you as easily as that post if you want to use a textview to display your text. I've done this extensively in my app, and basically you still need to compute the size of the text and grow the textview via a property associated layout height constraint. As far as your code, why don't you check first to see if the text ends with a `\n` and if so, add a character to it like `A` and compute the size based on that? – rvijay007 Jul 22 '14 at 17:27
  • How did you fix this? – jonypz May 10 '16 at 16:12

1 Answers1

1

This question is the first search result on google when searching for the particular bug/feature. It is solvable, and the way to solve it is by providing an additional flag in the "options" parameter: NSStringDrawingUsesFontLeading

The flag forces the method to use the line spacing of the font to calculate the range of text occupancy, which is the distance from the bottom of each line to the bottom of the next line (Ref: https://www.programmersought.com/article/6564672405/).

I've also found that you might need to add som additional padding to the height property of the resulting rectangle depending on which font is used.

CGRect rect = [text boundingRectWithSize:CGSizeMake(self.cellSize.width, CGFLOAT_MAX)
                                   options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                attributes:@{NSFontAttributeName:[UIFont fontWithName:@"AvenirNext-Medium" size:14.0]}
                                   context:nil];
Mani
  • 1,597
  • 15
  • 19