简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM