關於用Swift 4.0設定Label多彩文字AttributedText問題
阿新 • • 發佈:2019-01-07
最近由於開發需要,需要將Label的文字設定才如圖樣式
由於使用的swift開發,所以從網上搜索,大部分答案是這樣的
let minuteString = String(15)
let secondString = String(54)
let hintString = NSMutableAttributedString(string: minuteString + "分" + secondString + "秒")
//獲取要調整顏色的文字位置,調整顏色
let range1: NSRange = (hintString.string as NSString).range(of:minuteString)
hintString.addAttribute(kCTForegroundColorAttributeName as NSAttributedStringKey, value: UIColorFromRGB(rgbValue: 0xFF8617), range: range1)
let range2: NSRange = (hintString.string as NSString).range(of:secondString)
hintString.addAttribute(kCTForegroundColorAttributeName as NSAttributedStringKey, value: UIColorFromRGB(rgbValue: 0xFF8617), range: range2)
myLabel.attributedText = hintString
然而沒什麼效果,很無奈是不是,最後修改如下,重點:
**將kCTForegroundColorAttributeName as NSAttributedStringKey 改為 NSAttributedStringKey.foregroundColor**
改完的整段程式碼是:
let minuteString = String(15)
let secondString = String(54)
let hintString = NSMutableAttributedString(string: minuteString + "分" + secondString + "秒")
//獲取要調整顏色的文字位置,調整顏色
let range1: NSRange = (hintString.string as NSString).range(of:minuteString)
hintString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColorFromRGB(rgbValue: 0xFF8617), range: range1)
let range2: NSRange = (hintString.string as NSString).range(of:secondString)
hintString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColorFromRGB(rgbValue: 0xFF8617), range: range2)
myLabel.attributedText = hintString
出效果了,走你