Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline text not getting ellipsized

I'm trying to draw ellipsized text on multiple lines inside a rectangle.

For NSLineBreakByTruncatingTail, the documentation states

The line is displayed so that the beginning fits in the container and the missing text at the end of the line is indicated by an ellipsis glyph. Although this mode works for multiline text, it is more often used for single line text.

but with that mode I only get a single line:

With NSLineBreakByTruncatingTail

However with NSLineBreakByWordWrapping, I don't get an ellipsis for overlong text:

With NSLineBreakByWordWrapping

Both pictures use the same code below (red background is the text drawing rectangle) and of course the same rectangle size, so 2 lines should definitely fit.

NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = <<see above>>;
paragraphStyle.alignment = NSTextAlignmentNatural;
NSDictionary* drawingAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [UIFont fontWithName:@"HelveticaNeue" size:36],
                                   NSFontAttributeName,
                                   paragraphStyle,
                                   NSParagraphStyleAttributeName,
                                   nil];

const CGRect rect = CGRectMake(...);
[@"I do not get ellipsized in any way" drawInRect:rect withAttributes:drawingAttributes];

Is there a way to combine ellipsizing with multiline rendering, as the documentation says? With a UILabel, I would only have to set the number of lines to something other than 1, but what about text rendering via code?

like image 614
AndiDog Avatar asked Jan 13 '14 13:01

AndiDog


1 Answers

I don't understand why you are using NSMutableParagraphStyle and drawInRect, probably I'll need more information about the context you are trying to work.

But using this simple technique:

UILabel *label = [[UILabel alloc] initWithFrame:(CGRect){0,0,300,100}];
label.numberOfLines = 0;
label.backgroundColor = [UIColor redColor];
label.center = self.view.center;
label.font = [UIFont fontWithName:@"HelveticaNeue" size:36];
label.textAlignment = NSTextAlignmentNatural;
label.lineBreakMode = NSLineBreakByTruncatingTail;
label.text = @"I do not get ellipsized in any way";

[self.view addSubview:label];

You will see the following result: enter image description here

My suggestion is to get rid of drawInRect in this case.

like image 149
southfox Avatar answered Nov 04 '22 15:11

southfox