Reputation: 85
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
}
}
Upvotes: 2
Views: 2918
Reputation: 1021
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. It has a method called 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
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
Upvotes: 4