For*_*Zhu 7 xcode objective-c textcolor uilabel ios
我尝试用编程方式使用不同颜色的文本设置UILabel,
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
[self.resultLabel setAttributedText:string];
Run Code Online (Sandbox Code Playgroud)
我得到了我的预期.但是,我有兴趣在story.storyboard中的storyboard中完成所有这些工作.任何人都可以帮我这样做.
这就是我要的,
使用故事板界面:

使用Swift 3和4:以
编程方式,您可以非常轻松地设置标签颜色.
extension NSMutableAttributedString {
func setColorForText(textToFind: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
if range != nil {
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
}
func setColoredLabel() {
var string: NSMutableAttributedString = NSMutableAttributedString(string: "My label with red blue and green colored text")
string.setColorForText(textToFind: "red", withColor: UIColor.red)
string.setColorForText(textToFind: "blue", withColor: UIColor.blue)
string.setColorForText(textToFind: "green", withColor: UIColor.green)
yourLabel.attributedText = string
}
Run Code Online (Sandbox Code Playgroud)
结果:

| 归档时间: |
|
| 查看次数: |
7344 次 |
| 最近记录: |