Ios Swift:在属性字符串中追加字符
我想更改字符串中所有字符的颜色。但我的代码只给出了字符串中的最后一个字符。我想在属性字符串中附加字符。我该怎么做 我的代码:Ios Swift:在属性字符串中追加字符,ios,swift,append,nsattributedstring,Ios,Swift,Append,Nsattributedstring,我想更改字符串中所有字符的颜色。但我的代码只给出了字符串中的最后一个字符。我想在属性字符串中附加字符。我该怎么做 我的代码: func test(){ var str:String = "test string" for i in 0...count(str)-1{ var test = str[advance(str.startIndex, i)] var attrString =
func test(){
var str:String = "test string"
for i in 0...count(str)-1{
var test = str[advance(str.startIndex, i)]
var attrString = NSAttributedString(string: toString(test), attributes: [NSForegroundColorAttributeName: rainbowColors()])
label.attributedText = attrString
}
}
在这种情况下,如果希望每个字符具有相同的彩虹颜色,则不需要附加字符。您可以执行以下操作:
label.attributedText = NSAttributedString(string: str, attributes: [NSForegroundColorAttributeName: rainbowColors()])
如果要附加字符,则需要使用NSMutableAttributeString。它有一个名为append的方法
鉴于您希望每个索引使用不同的颜色,请执行以下操作:
var str:String = "test string"
var attributedString = NSMutableAttributedString()
for (index, character) in enumerate(str) {
attributedString.appendAttributedString(NSAttributedString(string: String(character), attributes: [NSForegroundColorAttributeName: colorForIndex(index)]))
}
label.attributedText = attributedString
colorForIndex是一个需要实现的函数,用于获取特定索引的彩虹颜色
func colorForIndex(index: Int) -> UIColor {
let color = // your function to get the color
return color
}
如果您需要帮助来实现该功能,请查看此问题否,我希望每个字符都有不同的颜色。效果很好!我不知道枚举函数。谢谢你的帮助。你真厉害