我TTTAttributedLabel
要检测标签中包含的 URL,现在我还想检测@menions
. 为此,我UITapGestureRecognizer
在标签中添加了一个,并且在每次点击时,我都会检查点击的单词是否以 @ 开头,等等。
我的自定义逻辑工作正常,但现在的 URL 检测TTTAttributedLabel
已损坏。我尝试将委托设置为我的 UITapGestureRecognizer 并覆盖
override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
但仍未检测到 URL 点击。知道如何在标签上同时拥有这两种功能吗?
编辑,我的一些代码:
UITapGestureRcognizer 是这样初始化的:
commentLabel.isUserInteractionEnabled = true;
let labelTap = UITapGestureRecognizer(target: self, action: #selector(labelTapped(_:)))
labelTap.delegate = self
commentLabel.addGestureRecognizer(labelTap)
我的水龙头功能如下:
@objc func labelTapped(_ sender: UITapGestureRecognizer) {
// Find the character that was tapped...
let textLabel = sender.view as? UILabel
let tapLocation = sender.location(in: textLabel)
// init text storage
var textStorage: NSTextStorage? = nil
if let attributedText = textLabel?.attributedText {
textStorage = NSTextStorage(attributedString: attributedText)
}
let layoutManager = NSLayoutManager()
textStorage?.addLayoutManager(layoutManager)
// init text container
let textContainer = NSTextContainer(size: CGSize(width: textLabel?.frame.size.width ?? 0.0, height: (textLabel?.frame.size.height ?? 0.0) + 100))
textContainer.lineFragmentPadding = 0
textContainer.maximumNumberOfLines = textLabel?.numberOfLines ?? 0
if let lineBreakMode = textLabel?.lineBreakMode {
textContainer.lineBreakMode = lineBreakMode
}
layoutManager.addTextContainer(textContainer)
// Get the character that was tapped
let characterIndex = layoutManager.characterIndex(
for: tapLocation,
in: textContainer,
fractionOfDistanceBetweenInsertionPoints: nil)
// Now find the word that was tapped
let word = textLabel?.text?.getWordFromCharacteratIndex(characterIndex) // Another custom function I've built that returns the word form a character
// And match it with a mentioned user
// Some code to match the word with my mentions pattern
// ...........
}