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:
However with NSLineBreakByWordWrapping
, I don't get an ellipsis for overlong text:
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?
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:
My suggestion is to get rid of drawInRect in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With