簡體   English   中英

Swift:在屬性字符串中附加字符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM