UILabel attributedText具有多个换行模式 [英] UILabel attributedText with multiple line break modes

查看:243
本文介绍了UILabel attributedText具有多个换行模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要显示一个UILabel,其文本具有两种不同的样式(不同的颜色,部分文本以粗体显示).通过使用attributedText-property可以很容易地解决此问题.

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.

当我切换到使用attributedText时,我只能在尾部截断和自动换行之间进行选择.如果我希望尾巴被截断,则标签仅用尾巴截断呈现一行(即使它可以容纳10行).如果我选择自动换行,则尾部不会被截断,但是不会显示标签中不适合的行.

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.

推荐答案

设置行距时我错过了截断,但是我要做的就是将linebreakmode添加到段落样式中

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;

这篇关于UILabel attributedText具有多个换行模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆