使用backgroundcolor将referencedstring设置为label

时间:2016-08-24 15:49:35

标签: ios objective-c uilabel background-color

我有两个带衬里的Label,并使用attributionString设置backgroundColor。

NSString *string = @"This is a UILAbel with two lines";

NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc]initWithString:
                                            string];

[mutableString setAttributes:@{NSBackgroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, string.length)];

如果文本换行,它会将backgroundColor填充到右边框,而在第二行则会停在最后一个字符处。

但我希望第一行中的backgroundcolor也设置为最后一个字符。

Pic example

1 个答案:

答案 0 :(得分:0)

backgroundColor属性应用于表示标签的整个矩形。

要解决此问题,您需要根据内容动态调整UILabel的框架,以达到预期的效果。

UILabel上有一个名为sizeToFit的方法;试着打电话。

虽然我建议您使用autolayout并让标签根据约束自行调整大小。