I have a UITextView which displays an NSAttributedString. This string contains words that I'd like to make tappable, such that when they are tapped I get called back so that I can perform an action. I realise that UITextView can detect taps on a URL and call back my delegate, but these aren't URLs.
It seems to me that with iOS7 and the power of TextKit this should now be possible, however I can't find any examples and I'm not sure where to start.
I understand that it's now possible to create custom attributes in the string (although I haven't done this yet), and perhaps these will be useful to detecting if one of the magic words has been tapped? In any case, I still don't know how to intercept that tap and detect on which word the tap occurred.
Note that iOS 6 compatibility is not required.
I was able to solve this pretty simply with NSLinkAttributeName
Swift 2
This one might work OK with short link, multilink in a textview. It work OK with iOS 6,7,8.
With Swift 4 and iOS 11, you can create a subclass of
UITextView
and overridehitTest(_:with:)
orpoint(inside:with:)
with some TextKit implementation in order to make only someNSAttributedStrings
in it tappable.The following code shows how to create a
UITextView
that only reacts to taps on underlinedNSAttributedStrings
in it:InteractiveUnderlinedTextView.swift
ViewController.swift
Making custom link and doing what you want on the tap has become much easier with iOS 7. There is very good example at Ray Wenderlich