将 UILabel 分成具有单独背景的 2 行?
Break UILabel into 2 lines with separate background?
我想要我的文字在行上但有单独的背景。我如何使用 UILabel 实现此目的?
我尝试了填充等,但没有任何效果,如果我 select 标签的背景颜色,它只会显示单个红色框。
关于如何获得与图像相同的效果的任何帮助?
使用NSAttributesString
。创建一个UILabel
,创建一个NSAttributesString
。然后不使用标签的 setText
,而是使用您之前创建的字符串对象调用 setAttributedText
。
有关 Apple Documentation 的更多帮助
使用以下代码:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:self.yourLabel.text];
//EDITED
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, text.length/2)];
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(text.length/2, text.length/2)];
[self.yourLabel setAttributedText: text];
[mutableAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:selectedRange];
我想要我的文字在行上但有单独的背景。我如何使用 UILabel 实现此目的?
我尝试了填充等,但没有任何效果,如果我 select 标签的背景颜色,它只会显示单个红色框。
关于如何获得与图像相同的效果的任何帮助?
使用NSAttributesString
。创建一个UILabel
,创建一个NSAttributesString
。然后不使用标签的 setText
,而是使用您之前创建的字符串对象调用 setAttributedText
。
有关 Apple Documentation 的更多帮助
使用以下代码:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:self.yourLabel.text];
//EDITED
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, text.length/2)];
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(text.length/2, text.length/2)];
[self.yourLabel setAttributedText: text];
[mutableAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:selectedRange];