2016-11-17 75 views
0

我想知道如何制作五颜六色的字符串。指定颜色在字符串中更改。 Swift iOS

我的意思是:

我需要字符串是例如

FirstLetter - 白色,第二个 - 蓝色,第三 - 红色,来回 - 橙,第五 - 白等于是在环。

我GOOGLE了这行代码:

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

但它得到的位置和长度,但如何在指定的顺序改变颜色?

回答

0

您可以使用此:

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 
0

此方法为你做它(正确的斯威夫特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]) 
4

试试这个:

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