检测ASTextNode AsyncDisplayKit中的链接或URL

Muk*_*esh 3 uitextview ios asyncdisplaykit

我一直在尝试使用AsyncDisplayKit框架,我需要检测文本中的url.

我用过ASTextNode但找不到任何api来检测链接.

我读到有linkAttributeNames用于网址检测的属性,但无法找到任何示例如何做到这一点.

有人可以帮助我如何使用上述课程吗?

谢谢

Bas*_*Bas 6

对于Swift 3.0

func addLinkDetection(_ text: String, highLightColor: UIColor, delegate: ASTextNodeDelegate) {
    self.isUserInteractionEnabled = true
    self.delegate = delegate

    let types: NSTextCheckingResult.CheckingType = [.link]
    let detector = try? NSDataDetector(types: types.rawValue)
    let range = NSMakeRange(0, text.characters.count)
    if let attributedText = self.attributedText {
        let mutableString = NSMutableAttributedString()
        mutableString.append(attributedText)
        detector?.enumerateMatches(in: text, range: range) {
            (result, _, _) in
            if let fixedRange = result?.range {
                mutableString.addAttribute(NSUnderlineColorAttributeName, value: highLightColor, range: fixedRange)
                mutableString.addAttribute(NSLinkAttributeName, value: result?.url, range: fixedRange)
                mutableString.addAttribute(NSForegroundColorAttributeName, value: highLightColor, range: fixedRange)

            }
        }
        self.attributedText = mutableString
    }        
}
Run Code Online (Sandbox Code Playgroud)

将委托添加到viewController:

/// Delegate function for linkDetection
func textNode(_ textNode: ASTextNode, shouldHighlightLinkAttribute attribute: String, value: Any, at point: CGPoint) -> Bool {
    return true
}

func textNode(_ textNode: ASTextNode, tappedLinkAttribute attribute: String, value: Any, at point: CGPoint, textRange: NSRange) {
    guard let url = value as? URL else { return }
 }
Run Code Online (Sandbox Code Playgroud)