ioshyperlinkuitextviewselection

UITextView link selectable without rest of text being selectable


I'm trying to get a setup similar to what Facebook use (if they use a UITextView). I want links to be detected automatically however I don't want any other text in the UITextView selectable. So, the user can click on the link but is unable to select any other text.

Despite searching around, I've yet to come across a solution as for link selection to work it requires the whole of the text view to be selectable.


Solution

  • This answer is for iOS 10.3.x and below where your UIView is not embedded in a subview. For a more robust, modern answer, please see Cœur's answer below.

    You need to prevent the UITextView from becoming first responder.

    1. Subclass UITextView to your own custom class (MyTextView).

    2. Override canBecomeFirstResponder(). Here's an example in Swift:

    Swift 3:

    class MyTextView: UITextView {
        override func becomeFirstResponder() -> Bool {
            return false
        }
    }
    

    Swift 2:

    class MyTextView: UITextView {
        override func canBecomeFirstResponder() -> Bool {
            return false
        }
    }
    

    Any links detected will still be enabled. I tested this with a phone number.