Magnifique
Magnifique

Reputation: 137

Specifed color changing in string. Swift iOS

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?

Upvotes: 0

Views: 643

Answers (3)

entwicklerfuchs
entwicklerfuchs

Reputation: 156

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

Upvotes: 4

Craig Grummitt
Craig Grummitt

Reputation: 2995

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])

Upvotes: 0

DevB2F
DevB2F

Reputation: 5075

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

Upvotes: 0

Related Questions