iOS: 利用TextKit實(shí)現(xiàn)UILabel的高亮、可交互

TextKit的相關(guān)知識可以看這一篇文章:點(diǎn)我

要使UILabel用上TextKit,需要自定義UILabel

先看看使用這個自定義Label的demo

demo.gif

1. 自定義UILabel并創(chuàng)建TextKit三個核心對象

    /// NSAttributedString 子類 設(shè)置文本統(tǒng)一使用
    fileprivate lazy var textStorage = NSTextStorage()
    /// 布局管理器 負(fù)責(zé) 字形 布局
    fileprivate lazy var layoutManager = NSLayoutManager()
    /// 繪制區(qū)域
    fileprivate lazy var textContainer = NSTextContainer()

2.設(shè)置TextKit

    /// 準(zhǔn)備文本系統(tǒng)
    fileprivate func prepareTextSystem() {
        
        adjustsFontSizeToFitWidth = true
        
        // 打開交互
        isUserInteractionEnabled = true
        
        // 準(zhǔn)備文本內(nèi)容
        prepareText()
        
        // 設(shè)置對象的關(guān)系
        textStorage.addLayoutManager(layoutManager)
        layoutManager.addTextContainer(textContainer)
        
    }
    
    /// 準(zhǔn)備文本內(nèi)容 - 使用TextStorage 接管 label內(nèi)容
    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í)行,所以需要兩個構(gòu)造器里調(diào)用此方法
    // 代碼創(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的文本內(nèi)容
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基本設(shè)置完了。

3. 利用正則尋找需要高亮的內(nèi)容

例如微博需要高亮

  • 鏈接

  • @用戶

  • #話題#

  • 根據(jù)正則表達(dá)式在textStorage中尋找對應(yīng)的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. 設(shè)置屬性文本

找到相應(yīng)的range后就可以設(shè)置顏色、背景色等等屬性了

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
  • 點(diǎn)擊高亮部分
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let location = touches.first?.location(in: self) else {
            return
        }
        
        // 獲取點(diǎn)擊了第幾個字符
        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("點(diǎn)擊了\(str)鏈接")
                return
            }
        }
        
        for range in topicRanges ?? [] {
            if NSLocationInRange(index, range) {
                let str = (textStorage.string as NSString).substring(with: range)
                print("點(diǎn)擊了\(str)話題")
                return
            }
        }
        
        for range in atRanges ?? [] {
            if NSLocationInRange(index, range) {
                let str = (textStorage.string as NSString).substring(with: range)
                print("點(diǎn)擊了\(str)用戶"))
                return
            }
        }
    }
  • 創(chuàng)建代理協(xié)議
    當(dāng)點(diǎn)擊高亮文本后需要傳遞事件以及點(diǎn)擊的文本出去這時候可以利用代理協(xié)議。
protocol XXXLabelDelegate: NSObjectProtocol {
    func labelDidSelectedLink(text: String)
    func labelDidSelectedTopic(text: String)
    func labelDidSelectedAt(text: String)
}
weak var delegate: XXXLabelDelegate?

6. 重寫屬性

當(dāng)在外部使用時,例如:

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是沒有任何內(nèi)容的,因?yàn)橐呀?jīng)使用TextKit接管了UILabel,所以需要重寫屬性,給textStorage賦值然后再設(shè)置屬性文本即可

    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
        }
        
        // 設(shè)置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,非常感謝。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容