![](/img/trans.png)
[英]Replace attributed string into NSMutableAttributedString In Swift 3
[英]Swift : Append Characters in Attributed String
我想将颜色更改为字符串中的所有字符。 但是我的代码仅给出字符串中的最后一个字符。 我想在属性字符串中附加字符。 我怎样才能做到这一点 ?
我的代码:
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
}
}
在这种情况下,如果希望每个字符具有相同的彩虹色,则无需附加字符。 您可以执行以下操作:
label.attributedText = NSAttributedString(string: str, attributes: [NSForegroundColorAttributeName: rainbowColors()])
如果要附加字符,则需要使用NSMutableAttributedString。 它有一个称为append的方法。
鉴于您希望每个索引使用不同的颜色,请执行以下操作:
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是您需要实现的功能,以获取该特定索引的彩虹色
func colorForIndex(index: Int) -> UIColor {
let color = // your function to get the color
return color
}
如果您需要帮助来实现该功能,请查看以下问题iOS彩虹色数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.