UILabel attributedText with multiple line break modes

僤鯓⒐⒋嵵緔 提交于 2019-12-03 12:21:08

问题


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.


回答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;



回答2:


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




回答3:


try this:

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




回答4:


You can set up an NSParagraphStyle with any lineBreakMode you please, and apply it to the string using NSParagraphStyleAttributeName. I don't know if all of the values of NSLineBreakMode are supported, but I have no reason to believe they aren't.



来源:https://stackoverflow.com/questions/16831207/uilabel-attributedtext-with-multiple-line-break-modes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!