Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/113.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用swift在字符串中添加两种颜色_Ios_Swift_Uilabel_Nsattributedstring - Fatal编程技术网

Ios 使用swift在字符串中添加两种颜色

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}")

我有一个字符串,我想对其应用两种颜色,然后将该字符串插入UILabel。字符串可能如下所示:

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