iOS UITextView点击链接,取消背景高亮

class CustomTextView: UITextView {
    var tapLinkBlock: ((String) -> Void)?

    override func awakeFromNib() {
        super.awakeFromNib()

//取消手势
        if let gestureRecognizers = self.gestureRecognizers {
            for recognizer in gestureRecognizers {
                if let index = self.gestureRecognizers?.firstIndex(of: recognizer) {
                    self.gestureRecognizers?.remove(at: index)
                }
            }
        }
    }

    override func touchesEnded(_ touches: Set, with event: UIEvent?) {
        let touch = Array(touches)[0]
        if let view = touch.view {
            let point = touch.location(in: view)
            self.tappedAction(on: point)
        }
    }

    private func tappedAction(on point: CGPoint) {
        var location: CGPoint = point
        location.x -= self.textContainerInset.left
        location.y -= self.textContainerInset.top
        let charIndex = layoutManager.characterIndex(for: location, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        guard charIndex < self.textStorage.length else {
            return
        }
        var range = NSRange(location: 0, length: 0)
        if let attributedText = self.attributedText {
            if let link = attributedText.attribute(NSAttributedString.Key.link, at: charIndex, effectiveRange: &range) as? String {
//处理点击链接动作
                tapLinkBlock?(link)
            }
        }
    }
}

你可能感兴趣的:(iOS UITextView点击链接,取消背景高亮)