gpt4 book ai didi

ios - 字符串中的两个 UIColors 使用 swift

转载 作者:行者123 更新时间:2023-11-28 13:19:41 25 4
gpt4 key购买 nike

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

var theString = "Kr. 200 \u{00B7} Red bike"

在这个字符串中,我想在\u{00B7} 之前分开,所以下面的这个字符串是红色的。

"\u{00B7} Red bike"

我想我需要先将它分开然后使用某种属性文本或者我该怎么做?

let titleString = theString.componentsSeparatedByString("\u{00B7}")

最佳答案

使用属性字符串就可以了。创建一个 NSMutableAttributedString 变量,在其上应用属性。然后将其赋值给 UILabel 的 attributed text 属性。
这是一个示例:

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

关于ios - 字符串中的两个 UIColors 使用 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26961955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com