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?
I'd strongly recommend using a library that automatically detects URLs in text and converts them to links. Try:
Both are under MIT license.
I found a other solution:
I find a way to detect the link in a html text that you find from the internet you transform it into nsattributeString with :
My method allows you to detect the hyperlink without having to specify them.
first you create an extension of the tapgesturerecognizer :
}
then in you view controller you created a list of url and ranges to store all the links and the range that the attribute text contain:
to find the URL and the URLRange you can use :
then you implementing the handle tap :
and here we go!
I hope this solution help you like it help me.
Translating @samwize's Extension to Swift 4:
To set up the recognizer (once you colored the text and stuff):
...then the gesture recognizer:
I am extending @NAlexN original detailed solution, with @zekel excellent extension of
UITapGestureRecognizer
, and providing in Swift.Extending UITapGestureRecognizer
Usage
Setup
UIGestureRecognizer
to send actions totapLabel:
, and you can detect if the target ranges is being tapped on inmyLabel
.IMPORTANT: The
UILabel
line break mode must be set to wrap by word/char. Somehow,NSTextContainer
will assume that the text is single line only if the line break mode is otherwise.As I mentioned in this post, here is a light-weighted library I created specially for links in UILabel FRHyperLabel.
To achieve an effect like this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicula justo. Nam at urna neque. Maecenas ac sem eu sem porta dictum nec vel tellus.
use code:
For fully custom links, you'll need to use a UIWebView - you can intercept the calls out, so that you can go to some other part of your app instead when a link is pressed.