通常,使用以下扩展名可以轻松解决对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
不起作用。
有什么想法吗?