使用backgroundcolor将标签字符串设置为标签
问题描述:
我有两个标签,并使用一个归属字符串设置backgroundColor。使用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也设置为最后一个字符。
答
的backgroundColor
属性应用于代表所述标签的整个矩形。
要解决此问题,您需要根据其内容动态调整UILabel
的框架,以达到预期的效果。
UILabel
上有一个叫做sizeToFit
的方法;尝试调用它。
尽管我建议您使用autolayout,并让标签根据约束来调整自身大小。
你可以显示你的问题或你想要的图像。 –
你是如何得到正确的照片? –
您正在将背景颜色设置为红色...对我来说看起来很漂亮:p –