UILabel attributedText with multiple line break modes

16,617

Solution 1

I missed truncation when I set linespacing, but all I had to to was add linebreakmode to paragraphstyle

NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setLineSpacing:1.5];
[paragrahStyle setLineBreakMode:NSLineBreakByTruncatingTail];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:@"Long string that truncates"];
[attributedText addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [attributedText length])];

self.label.attributedText = attributedText;

Solution 2

They only way I've been able to get this to work is to not set a paragraph style.

Solution 3

try this:

[_text drawWithRect:_textRect options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil];

Share:
16,617
Ville Rinne
Author by

Ville Rinne

Updated on June 05, 2022

Comments

  • Ville Rinne
    Ville Rinne almost 2 years

    I have a requirement of showing a UILabel with text that has two different styles (different colours, parts of the text bolded). This is solved easily enough by using the attributedText-property.

    My problem is that the text may or may not be longer than what I can fit in my label. When using plain text everything works the way I want it to. The text is word wrapped to fit the number of lines in the label and the tail is truncated if/when the text is longer than can be shown in the label.

    When I switch to using attributedText I am only able to choose between tail truncation and word wrapping. If I want the tail truncated the label only renders a single line with the truncated tail (even though it could fit 10 lines). If I choose word wrapping then the tail is not truncated but the lines that cannot fit in the label are simply not shown.

    My content string does not contain any line breaks, it is simply one long string.