TextKit的相關知識可以看這一篇文章:點我
要使UILabel
用上TextKit
绢掰,需要自定義UILabel
先看看使用這個自定義Label的demo
1. 自定義UILabel
并創(chuàng)建TextKit
三個核心對象
/// NSAttributedString 子類 設置文本統(tǒng)一使用
fileprivate lazy var textStorage = NSTextStorage()
/// 布局管理器 負責 字形 布局
fileprivate lazy var layoutManager = NSLayoutManager()
/// 繪制區(qū)域
fileprivate lazy var textContainer = NSTextContainer()
2.設置TextKit
/// 準備文本系統(tǒng)
fileprivate func prepareTextSystem() {
adjustsFontSizeToFitWidth = true
// 打開交互
isUserInteractionEnabled = true
// 準備文本內容
prepareText()
// 設置對象的關系
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
}
/// 準備文本內容 - 使用TextStorage 接管 label內容
fileprivate func prepareText() {
if let attributedText = attributedText {
textStorage.setAttributedString(attributedText)
}else if let text = text {
textStorage.setAttributedString(NSAttributedString(string: text))
}else {
textStorage.setAttributedString(NSAttributedString(string: ""))
return
}
-
上一步需要在label初始化的時候執(zhí)行,所以需要兩個構造器里調用此方法
// 代碼創(chuàng)建
override init(frame: CGRect) {
super.init(frame: frame)
prepareTextSystem()
}
// xib創(chuàng)建
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareTextSystem()
}
-
指定文本繪制區(qū)域
override func layoutSubviews() {
super.layoutSubviews()
textContainer.size = bounds.size
}
-
繪制textStorage的文本內容
override func drawText(in rect: CGRect) {
// 繪制背景
let range = NSRange(location: 0, length: textStorage.length)
layoutManager.drawBackground(forGlyphRange: range, at: CGPoint(x: 0, y: 0))
// 繪制字形
layoutManager.drawGlyphs(forGlyphRange: range, at: CGPoint(x: -5, y: 0))
}
注意:必須先繪制背景才能繪制字形!否則背景會覆蓋字形
到此滴劲,TextKit基本設置完了攻晒。
3. 利用正則尋找需要高亮的內容
例如微博需要高亮
鏈接
@用戶
#話題#
根據(jù)正則表達式在textStorage中尋找對應的range
private func findRanges(pattern: String) -> [NSRange]? {
guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else {
return nil
}
let matches = regx.matches(in: textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length))
var ranges = [NSRange]()
for match in matches {
ranges.append(match.rangeAt(0))
}
return ranges
}
- 定義計算型屬性保存ranges
/// 鏈接
var urlRanges: [NSRange]? {
let pattern = "\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))"
return findRanges(pattern: pattern)
}
/// 話題
var topicRanges: [NSRange]? {
let pattern = "#[^#]+#"
return findRanges(pattern: pattern)
}
/// @用戶
var atRanges: [NSRange]? {
let pattern = "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]{2,30}"
return findRanges(pattern: pattern)
}
4. 設置屬性文本
找到相應的range后就可以設置顏色、背景色等等屬性了
fileprivate func setupTextAttributes() {
textStorage.addAttributes([NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor],
range: NSRange(location: 0, length: textStorage.length))
for range in urlRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
for range in topicRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
for range in atRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
}
5. 交互
- 要使
UILabel
可交互前提是打開交互
isUserInteractionEnabled = true
- 點擊高亮部分
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let location = touches.first?.location(in: self) else {
return
}
// 獲取點擊了第幾個字符
let index = layoutManager.glyphIndex(for: location, in: textContainer)
// 判斷index是否在 range里
for range in urlRanges ?? [] {
if NSLocationInRange(index, range) {
let str = (textStorage.string as NSString).substring(with: range)
print("點擊了\(str)鏈接")
return
}
}
for range in topicRanges ?? [] {
if NSLocationInRange(index, range) {
let str = (textStorage.string as NSString).substring(with: range)
print("點擊了\(str)話題")
return
}
}
for range in atRanges ?? [] {
if NSLocationInRange(index, range) {
let str = (textStorage.string as NSString).substring(with: range)
print("點擊了\(str)用戶"))
return
}
}
}
- 創(chuàng)建代理協(xié)議
當點擊高亮文本后需要傳遞事件以及點擊的文本出去這時候可以利用代理協(xié)議哑芹。
protocol XXXLabelDelegate: NSObjectProtocol {
func labelDidSelectedLink(text: String)
func labelDidSelectedTopic(text: String)
func labelDidSelectedAt(text: String)
}
weak var delegate: XXXLabelDelegate?
6. 重寫屬性
當在外部使用時炎辨,例如:
let label = XXXLabel()
label.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
label.text = "@百度 https://www.baidu.com" // 或者 label.attributedText = “@百度 https://www.baidu.com”
label.font = UIFont.systemFont(ofSize: 15)
這時候label是沒有任何內容的,因為已經使用TextKit接管了UILabel聪姿,所以需要重寫屬性,給textStorage賦值然后再設置屬性文本即可
override var text: String? {
didSet {
prepareText()
}
}
override var attributedText: NSAttributedString? {
didSet {
prepareText()
}
}
override var font: UIFont! {
didSet {
prepareText()
}
}
override var textColor: UIColor! {
didSet {
prepareText()
}
}
fileprivate func prepareText() {
if let attributedText = attributedText {
textStorage.setAttributedString(attributedText)
}else if let text = text {
textStorage.setAttributedString(NSAttributedString(string: text))
}else {
textStorage.setAttributedString(NSAttributedString(string: ""))
return
}
// 設置Text屬性
setupTextAttributes()
}
fileprivate func setupTextAttributes() {
textStorage.addAttributes([NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor],
range: NSRange(location: 0, length: textStorage.length))
for range in urlRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
for range in topicRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
for range in atRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
}
GitHub
覺得不錯的給個star碴萧,非常感謝。