我想知道如何制作彩色弦乐。
我的意思是:
我需要字符串作为例如
FirstLetter - 白色,第二个 - 蓝色,第三个 - 红色,第四个 - 橙色,第五个 - 白色,依此类推。
我用Google搜索了这行代码:
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
但它获取位置和长度,但如何按指定顺序更改颜色?
答案 0 :(得分: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)
}
答案 1 :(得分: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
答案 2 :(得分:0)
此方法将为您完成(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])