当属性文本包含表情符号时,如何使用swift处理UILabel中各个单词的轻击?

时间:2018-08-25 09:05:30

标签: swift uilabel nsattributedstring emoji clickable

通常,使用以下扩展名可以轻松解决对UILabel内部特定范围内的轻击(或特定单词的轻击)的检测:

extension UITapGestureRecognizer {

    func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
        let storage = NSTextStorage(attributedString: label.attributedText!)

        let layoutManager = NSLayoutManager()
        storage.addLayoutManager(layoutManager)

        let textContainer = NSTextContainer(size: label.frame.size)
        layoutManager.addTextContainer(textContainer)

        textContainer.lineFragmentPadding = 0.0

        var glyphRange = NSRange()
        layoutManager.characterRange(forGlyphRange: targetRange, actualGlyphRange: &glyphRange)

        let glyphRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
        let touchPoint = self.location(ofTouch: 0, in: label)

        return glyphRect.contains(touchPoint)
    }

}

但是,如果属性文本包含表情符号,则此方法将无效。例如:

  

Lorem ipsum dolor TAP_HERE lorem ipsum

工作正常,但是:

  

Lorem ipsum dolor TAP_HERE lorem ipsum

不起作用。

有什么想法吗?

0 个答案:

没有答案