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