Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boundingRectWithSize ignores line breaks

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?

like image 542
Lukas Spieß Avatar asked Jul 22 '14 15:07

Lukas Spieß


1 Answers

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];
like image 59
Mani Avatar answered Sep 23 '22 03:09

Mani