0

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
        // ...........
    }
4

2 回答 2

2

您可以尝试使用其他标签来检测#hashtags、@usernames 和超链接

https://github.com/optonaut/ActiveLabel.swift

于 2020-07-30T14:01:28.177 回答
0

我想到了。UITapGestureRecognizer 在被识别后取消了点击事件,因此通过设置labelTap.cancelsTouchesInView = false为 my UITapGestureRegognizer,触摸甚至被传递给两个回调。而且我什至不需要实现shouldRecognizeSimultaneouslyWith otherGestureRecognizerdelgate 方法,因为TTTAttributedLabel它使用触摸事件而不是 UITapGestureRecognizer` 进行 URL 检测。

于 2020-07-30T14:16:11.567 回答