2

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

No, I want each every character to have different color.
Worked well ! I didn't know enumerate function. Thanks for helping. You rock ! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.