Tomas Brennan
Tomas Brennan

Reputation: 41

iOS drawInRect:attributes perform text truncation with multiple lines

How can I draw a long text string in a rect with tail truncation? I tried to use drawInRect:withAttributes: with NSLineBreakByTruncatingTail paragraph style, but it always renders text on a single line. It only renders multi-line text with NSLineBreakByWordWrapping and NSLineBreakByCharWrapping break modes and when using this option there is no truncation. Is there any property that I need to set on the paragraph style in order to make this happen? Or is this simply no longer supported, in which case I can see no alternative other than continuing to use deprecated methods. The deprecated method drawInRect:withFont:lineBreakMode:alignment:worked correctly.

Upvotes: 4

Views: 1168

Answers (1)

xZenon
xZenon

Reputation: 655

It is possible.

You are right - you can't use NSLineBreakByTruncatingTail paragraph style because it will show only single line of truncated text.

Instead of deprecated drawInRect:withFont:lineBreakMode:alignment: you should use drawWithRect:options:attributes:context:

[string drawWithRect:CGRectMake(x, y, width, height)
             options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine
          attributes:@{NSFontAttributeName:<font>, NSForegroundColorAttributeName:<color>}
             context:nil];

Upvotes: 5

Related Questions