2016-08-05 28 views
-1

我需要一組屬性文本。我需要每個元素的顏色根據其在陣列中的位置而改變(這將通過HSV來實現,因爲色調值將與位置相關)。該數組根據用戶輸入而有所不同,我不知道如何編寫它以便自動更改顏色。我把用戶的輸入分成了一個數組,那麼我怎樣才能將每個單詞轉換爲屬性文本?我完全不知道如何做到這一點,所以提前感謝您的幫助。如何製作屬性文本數組

+0

這將幫助,如果你能更具體。也許提供一些你已經嘗試過的代碼。 – Zaz

回答

1

您可以通過使用enumeratemap更加簡潔做到這一點:

let strings = ["The", "Cat", "In", "The", "Hat"] 

let attribStrings = strings.enumerate().map { index, element in 
    return NSAttributedString(string: element, attributes: [NSForegroundColorAttributeName:UIColor(hue: CGFloat(index)/CGFloat(strings.count), saturation: 0.5, brightness: 0.5, alpha: 1.0)]) 
} 

您的陣列中的每個原始元素與UIColor(hue: CGFloat(index)/CGFloat(strings.count), saturation: 0.5, brightness: 0.5, alpha: 1.0)文本顏色映射到NSAttributedString。您應該根據自己的喜好調整飽和度和亮度。

輸出到UILabel會是什麼樣子:

enter image description here

0

您可以使用NSForegroundColorAttributeName來更改NSAttributedString的顏色。我在下面列出了一個樣本,它創建了64種不同的顏色 。

func colorUsingHSV(index : Int, total : Int) -> UIColor 
{ 
    return UIColor(hue: CGFloat((CGFloat(index)/CGFloat(total))), saturation: 1.0, brightness: 1.0, alpha: 1.0) 
} 

func generateAttributeText() 
{ 
    var attrStrings = [NSAttributedString]() 
    for i in 1...64 
    { 
    let attrString: NSMutableAttributedString = NSMutableAttributedString(string: "Text") 
    attrString.addAttribute(NSForegroundColorAttributeName, value: colorUsingHSV(i,total: 64), range: NSMakeRange(0, attrString.length)) 

    attrStrings.append(attrString) 
    } 
}