I have a UITextView inside a UITableViewCell subclass. It has editable and userInteractionEnabled both set to NO. This allows the UITextView to detect data such as links and phone numbers. The data is detected correctly, but because userInteraction is disabled, it cannot respond to taps on that data. If I set userInteractionEnabled to YES, it works fine, but then the UITableViewCell cannot be selected since the UITextView swallows the touch.
I want to follow the link if the user taps on it, but I want didSelectRowAtIndexPath: to be called if the tap is on basic text.
I think the right approach is to subclass UITextView and pass touches to the cell, but I can't seem to find a way to detect whether or not the tap was on a link.
This is a similar question, but the answer will just pass all touches to the cell. I want to only pass the touches if they are NOT on a piece of detected data. issue enabling dataDetectorTypes on a UITextView in a UITableViewCell
1. Using
hitTest(_:with:)UIViewhas a method calledhitTest(_:with:)that has the following definition:UITextViewbeing a subclass ofUIView, you can implement this method in any subclass ofUITextViewyou may want to create.The following Swift 3 example shows a
UITableViewControllerthat contains a single staticUITableViewCell. TheUITableViewCellembeds aUITextView. Any tap on a link inside theUITextViewwill launch Safari app; any tap on basic text inside theUITextViewwill trigger a push segue to the followingUIViewController.LinkTextView.swift
TextViewCell.swift
TableViewController.swift
2. Using
point(inside:with:)As an alternative to override
hitTest(_:with:), you can usepoint(inside:with:).point(inside:with:)has the following declaration:The following code shows how to implement
point(inside:with:)instead ofhitTest(_:with:)in yourUITextViewsubclass:LinkTextView.swift
The complete project is available on this GitHub repo: LinkTextViewCell.
You can learn more about managing a
UITextViewinside aUITableViewCellby reading Swifty Approach to Handling UITextViews With Links in Cells.You can learn more about the difference between
hitTest(_:with:)andpoint(inside:with:)by reading Apple's Guide and Sample Code: "Event Delivery: The Responder Chain".