I have been searching this for hours but I've failed. I probably don't even know what I should be looking for.
Many applications have text and in this text are web hyperlinks in rounded rect. When I click them UIWebView
opens. What puzzles me is that they often have custom links, for example if words starts with # it is also clickable and the application responds by opening another view. How can I do that? Is it possible with UILabel
or do I need UITextView
or something else?
Here is a swift version of NAlexN's answer.
}
You can then create an instance of that class inside your
viewDidLoad
method like this:It's better to have a custom attribute to use when a character is tapped. Now, it's the
NSLinkAttributeName
, but could be anything and you can use that value to do other things other than opening a url, you can do any custom action.Like there is reported in earlier awnser the UITextView is able to handle touches on links. This can easily be extended by making other parts of the text work as links. The AttributedTextView library is a UITextView subclass that makes it very easy to handle these. For more info see: https://github.com/evermeer/AttributedTextView
You can make any part of the text interact like this (where textView1 is a UITextView IBoutlet):
And for handling hashtags and mentions you can use code like this:
This generic method works too !
And you can call the method with
Here's a drop-in Objective-C category that enables clickable links in existing
UILabel.attributedText
strings, exploiting the existingNSLinkAttributeName
attribute.This would be a bit cleaner done via a UILabel subclass (ie none of the objc_getAssociatedObject mess), but if you are like me you prefer to avoid having to make unnecessary (3rd party) subclasses just to add some extra function to existing UIKit classes. Also, this has the beauty that it adds clickable-links to any existing UILabel, eg existing
UITableViewCells
!I've tried to make it as minimally invasive as possible by using the existing
NSLinkAttributeName
attribute stuff already available in NSAttributedString. So its a simple as:Basically, it works by adding a
UIGestureRecognizer
to your UILabel. The hard work is done ingestureRecognizerShouldBegin:
, which re-layouts the attributedText string to find out which character was tapped on. If this character was part of a NSLinkAttributeName then the gestureRecognizer will subsequently fire, retrieve the corresponding URL (from the NSLinkAttributeName value), and open the link per the usual[UIApplication.sharedApplication openURL:url]
process.Note - by doing all this in
gestureRecognizerShouldBegin:
, if you dont happen to tap on a link in the label, the event is passed along. So, for example, your UITableViewCell will capture taps on links, but otherwise behave normally (select cell, unselect, scroll, ...).I've put this in a GitHub repository here. Adapted from Kai Burghardt's SO posting here.
I follow this version,
Swift 4:
Call Example: