Ios 使用swift在字符串中添加两种颜色
我有一个字符串,我想对其应用两种颜色,然后将该字符串插入UILabel。字符串可能如下所示:Ios 使用swift在字符串中添加两种颜色,ios,swift,uilabel,nsattributedstring,Ios,Swift,Uilabel,Nsattributedstring,我有一个字符串,我想对其应用两种颜色,然后将该字符串插入UILabel。字符串可能如下所示: var theString = "Kr. 200 \u{00B7} Red bike" 在这个字符串中,我希望在\u{00B7}之前分开,以便下面的字符串是红色的 "\u{00B7} Red bike" 我想我需要先把它分开,然后使用某种属性文本,或者我该怎么做 let titleString = theString.componentsSeparatedByString("\u{00B7}")
var theString = "Kr. 200 \u{00B7} Red bike"
在这个字符串中,我希望在\u{00B7}之前分开,以便下面的字符串是红色的
"\u{00B7} Red bike"
我想我需要先把它分开,然后使用某种属性文本,或者我该怎么做
let titleString = theString.componentsSeparatedByString("\u{00B7}")
使用属性化字符串可以很好地工作。创建NSMutableAttributedString变量,对其应用属性。然后将其分配给UILabel的属性文本属性。
以下是一个示例:
var myString:NSString = "Blue Text Red Text"
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: myString as String, attributes: nil)
myMutableString.addAttribute(NSForegroundColorAttributeName, value:UIColor.blueColor(), range: NSRange(location:0,length:9))
myMutableString.addAttribute(NSForegroundColorAttributeName, value:UIColor.redColor(), range: NSRange(location:10,length:7))
yourlabel.attributedText = myMutableString