Swift 修改字符串的範圍顏色 NSAttributedString NSMutableAttributedString

Swift 修改字符串的範圍顏色 NSAttributedString NSMutableAttributedString

需求:

獲取 StoryBoard 中字義的 Label,根據須要設置 Label 內文字的一部分爲一個顏色,另外一部分爲另外一個顏色,以下圖swift

result.jpg

實現所需知識

這裏須要用到 NSAttributedStringNSMutableAttributedString,這兩個都是 iOS 中最經常使用的文字表示形式,它包含文字的顏色,邊框,大小,字體等等等等,全部 NSAttributedString.Key 裏列舉的屬性均可以定義。app

官方文檔中的說明: https://developer.apple.com/documentation/foundation/nsattributedstring/key

先說說區別:字體

類名 說明
NSAttributedString 一次生成,不能修改屬性,不能修改文字內容
NSMutableAttributedString 能夠修改內部的屬性值,不能修改文字內容

NSAttributedString.Key 一些經常使用屬性的說明

屬性值 說明
.foregroundColor 文字顏色
.strokeColor 描邊顏色
.strokeWith 描邊大小
.font 字體: 相關字體的屬性去字體裏面設置,大小,字體類型等等

實現

我是在一個 TableViewController 中修改 Cell 的某個 Label ,外面的代碼不寫了,只解釋裏面的關於修改字符的部分spa

// 1. 獲取 StoryBoard 中 Label 的原有屬性
let attributes = cell.labelTitle.attributedText!.attributes(at: 1, effectiveRange: NSRangePointer(bitPattern: 0))
    
// 2. 建立新的可編輯的字符對象
let mString = NSMutableAttributedString(string: String(sample.temperature),
                                        attributes: attributes)
    
// 3. 在生成的 NSMutableAttributedString 對象中修改前兩位的顏色
mString.setAttributes(
    [NSAttributedString.Key.foregroundColor : UIColor.black],
    range: NSRange(location: 0, length: 2)
)
    
// 4. 修改後面剩餘字符的顏色
mString.setAttributes(
    [NSAttributedString.Key.foregroundColor : Colors.magenta],
    range: NSRange(location: 3, length: mString.string.count - 3)
)

// 5. 把修改好的 NSMutableAttributedString 從新賦值給 Label
cell.labelTitle.attributedText = mString

結果

after.png

相關文章
相關標籤/搜索