将属性字符串设置为带有背景颜色的标签

Setting attributedstring to label with backgroundcolor

我有两个带内衬的 Label 并使用 attributedString 设置 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 属性 应用于表示标签的整个矩形。

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

UILabel 上有一个名为 sizeToFit 的方法;尝试调用它。

尽管我建议您使用自动布局并让标签根据约束自行调整大小。