簡體   English   中英

指定的顏色以字符串形式更改。 迅捷的iOS

[英]Specifed color changing in string. Swift iOS

我想知道如何制作彩色琴弦。

我的意思是:

我將需要字符串例如

第一字母-白色,第二藍色,第三紅色,第四橙色,第五白色等在循環中。

我用谷歌搜索了以下代碼:

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length: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)
}

您可以使用此:

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

此方法將為您做到(針對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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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