How do you make a UITextView detect link part in the text and still have userInteractionDisabled?

前端 未结 3 944
遇见更好的自我
遇见更好的自我 2020-12-19 03:08

I have a textView that is layered on a tableView cell. I need the user to click on the tableView row to open a viewController but if the textView has a link it must be click

3条回答
  •  萌比男神i
    2020-12-19 03:45

    If you are trying to add a UITextView with links to a cell, and want didSelectRow to be called when the user taps on anything but the link, then you should use hitTest:withEvent:

    Swift 3

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // location of the tap
        var location = point
        location.x -= self.textContainerInset.left
        location.y -= self.textContainerInset.top
    
        // find the character that's been tapped
        let characterIndex = self.layoutManager.characterIndex(for: location, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        if characterIndex < self.textStorage.length {
            // if the character is a link, handle the tap as UITextView normally would
            if (self.textStorage.attribute(NSLinkAttributeName, at: characterIndex, effectiveRange: nil) != nil) {
                return self
            }
        }
    
        // otherwise return nil so the tap goes on to the next receiver
        return nil
    }
    

    I wrote an article about this with a bit more details.

提交回复
热议问题