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 為對應效果即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM