[英]Swift : Append Characters in Attributed String
I want to change color to all characters in string. 我想将颜色更改为字符串中的所有字符。 But my code is giving just last character in string.
但是我的代码仅给出字符串中的最后一个字符。 I want to append characters in attributed string.
我想在属性字符串中附加字符。 How can I do this ?
我怎样才能做到这一点 ?
My Code : 我的代码:
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
}
}
In this case you don't need to append characters if you want each character to have the same rainbow color. 在这种情况下,如果希望每个字符具有相同的彩虹色,则无需附加字符。 You could do the following:
您可以执行以下操作:
label.attributedText = NSAttributedString(string: str, attributes: [NSForegroundColorAttributeName: rainbowColors()])
If you want to append characters you need to use NSMutableAttributedString. 如果要附加字符,则需要使用NSMutableAttributedString。 It has a method called append.
它有一个称为append的方法。
Given the fact that you want a different color for each index do the following: 鉴于您希望每个索引使用不同的颜色,请执行以下操作:
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 is a function you need to implement to get the rainbow color for that particular index colorForIndex是您需要实现的功能,以获取该特定索引的彩虹色
func colorForIndex(index: Int) -> UIColor {
let color = // your function to get the color
return color
}
If you need help to implement that function take a look at this question iOS rainbow colors array 如果您需要帮助来实现该功能,请查看以下问题iOS彩虹色数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.