iOS - Swift UILabel 實現部分文字添加下滑線

需求:對 UILabel 的文本中部分文字標記下劃線

實現:對於 UILabel 文本設置樣式的話,我們可以直接創建 NSMutableAttributedString 對象,然後使用 addAttribute 對它添加一些樣式,最後賦值給 UILabel 的 attributedText 屬性即可。

示例:

let label: UILabel = UILabel()
let helloWorld: String = "Hello World"
let helloWorldAttrStr: NSMutableAttributedString = NSMutableAttributedString(string: helloWorld)
let range: NSRange = NSRange(location: 0, length: helloWorld.count)

helloWorldAttrStr.addAttribute(NSAttributedString.Key.underlineStyle, value: 1, range: range)

label.attributedText = helloWorldAttrStr

如果要對部分的文本添加下劃線,可以參考 iOS - Swift 實現字符串查找子字符串的位置 - sims - 博客園 (cnblogs.com) 獲取到子字符串的位置,如下:

let label: UILabel = UILabel()
let markStr: String = "Wo"
let helloWorld: String = "Hello World"
let helloWorldAttrStr: NSMutableAttributedString = NSMutableAttributedString(string: helloWorld)
let markStrRange: Range = helloWorld.range(of: markStr)!
let location = helloWorld.distance(from: helloWorld.startIndex, to: markStrRange.lowerBound)
let range: NSRange = NSRange(location: location, length: markStr.count)

helloWorldAttrStr.addAttribute(NSAttributedString.Key.underlineStyle, value: 1, range: range)

label.attributedText = helloWorldAttrStr

上面的代碼是實現下劃線的效果,其它效果可以替換  NSAttributedString.Key.underlineStyle 爲對應效果即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章