iosuitextviewnsattributedstring

UITextView: Disable selection, allow links


I have a UITextView which displays an NSAttributedString. The textView's editable and selectable properties are both set to false.

The attributedString contains a URL and I'd like to allow tapping the URL to open a browser. But interaction with the URL is only possible if the selectable attribute is set to true.

How can I allow user interaction only for tapping links, but not for selecting text?


Solution

  • I find the concept of fiddling with the internal gesture recognizers a little scary, so tried to find another solution. I've discovered that we can override point(inside:with:) to effectively allow a "tap-through" when the user isn't touching down on text with a link inside it:

    // Inside a UITextView subclass:
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    
        guard let pos = closestPosition(to: point) else { return false }
    
        guard let range = tokenizer.rangeEnclosingPosition(pos, with: .character, inDirection: .layout(.left)) else { return false }
    
        let startIndex = offset(from: beginningOfDocument, to: range.start)
    
        return attributedText.attribute(.link, at: startIndex, effectiveRange: nil) != nil
    }   
    

    This also means that if you have a UITextView with a link inside a UITableViewCell, tableView(didSelectRowAt:) still gets called when tapping the non-linked portion of the text :)