0

I'm wondering how to make colorful string.

What I mean is:

I will need string to be for example

FirstLetter - white, second - blue, third - red , forth - orange , fifth - white and so on so in loop.

I googled this line of code:

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))

but it gets location and length, but how to make changing color in specified order?

3 Answers 3

4

try this:

let color : [UIColor] = [.white, .blue, .red, .orange]


let plainString = "Hello World"
let str = NSMutableAttributedString(string: plainString)

for var i in 0..<plainString.characters.count {
    let range =  NSMakeRange(i, 1)
    let newColor = color[i % color.count]

    str.addAttribute(NSForegroundColorAttributeName, value: newColor, range: range)
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use this:

let text = NSMutableAttributedString(string: "ABC")
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: NSMakeRange(1, 2))
thelabel.attributedText = text

Comments

0

This method will do it for you (Correct for Swift 3/Xcode 8)

import UIKit

var str = "Hello, playground"

func colorText(str:String,textColors:[UIColor])->NSMutableAttributedString {
    let myMutableString = NSMutableAttributedString(string: str)
    var charNum = 0
    repeat {
        for color in textColors {
            if charNum>=myMutableString.length {
                return myMutableString
            }
            myMutableString.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location:charNum,length:1))
            charNum+=1
        }
    } while true
}


let coloredText = colorText(str: str,textColors:[.white,.blue,.red,.orange])

Comments

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.