? 如果需要一個字符前后文字顏色不一樣,也就是說一個字符串分成多個部分,每個部分的屬性(顏色,字體,大小等)不一樣,那就是富文本文字 NSMutableAttributedString
直接上代碼了
let str = "今宵杯中映著明月 物華天寶人杰地靈"? ? ? ?
let attrStr = NSMutableAttributedString.init(string: str)
attrStr.addAttribute(NSAttributedStringKey.foregroundColor, value:UIColor.orange, range:NSRange.init(location:0, length: 8))
attrStr.addAttribute(NSAttributedStringKey.foregroundColor, value:UIColor.red, range:NSRange.init(location:9, length: 8))
label1.attributedText = attrStr
/// 僅字體和大小? ? ? ?
label2.attributedText = NSAttributedString.init(string:"這是一串文字", attributes: [NSAttributedStringKey.backgroundColor:UIColor.cyan,? NSAttributedStringKey.font:UIFont.systemFont(ofSize:28)])
/// 背景色? ? ? ?
label3.attributedText = NSAttributedString.init(string:"這是一個有背景色的文字", attributes: [NSAttributedStringKey.backgroundColor:UIColor.green,? NSAttributedStringKey.font:UIFont.systemFont(ofSize:18)])
/// 陰影? ? ? ?
let shadow = NSShadow.init()? ? ? ?
shadow.shadowColor = UIColor.red? ? ? ?
shadow.shadowOffset = CGSize.init(width: 2, height: 2)? ? ? ?
label4.attributedText = NSAttributedString.init(string:"這是一個有陰影的文字", attributes: [NSAttributedStringKey.foregroundColor:UIColor.red,? NSAttributedStringKey.font:UIFont.systemFont(ofSize:18), NSAttributedStringKey.shadow: shadow])
/// 下劃線? ? ? ?
label5.attributedText = NSAttributedString.init(string:"這是一個有下劃線的文字", attributes: [NSAttributedStringKey.foregroundColor:UIColor.purple,? NSAttributedStringKey.font:UIFont.systemFont(ofSize:18), NSAttributedStringKey.underlineStyle:NSUnderlineStyle.styleSingle.rawValue])
代碼圖:

效果圖:

轉(zhuǎn)載請注明出處,謝謝。