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:)
UIView
has a method calledhitTest(_:with:)
that has the following definition:UITextView
being a subclass ofUIView
, you can implement this method in any subclass ofUITextView
you may want to create.The following Swift 3 example shows a
UITableViewController
that contains a single staticUITableViewCell
. TheUITableViewCell
embeds aUITextView
. Any tap on a link inside theUITextView
will launch Safari app; any tap on basic text inside theUITextView
will 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 yourUITextView
subclass:LinkTextView.swift
The complete project is available on this GitHub repo: LinkTextViewCell.
You can learn more about managing a
UITextView
inside aUITableViewCell
by 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".