swift——富文本文字的簡單使用

? 如果需要一個字符前后文字顏色不一樣,也就是說一個字符串分成多個部分,每個部分的屬性(顏色,字體,大小等)不一樣,那就是富文本文字 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)載請注明出處,謝謝。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容