Michael
Michael

Reputation: 303

Tappable Dynamic Links With UILabel

I am looking for a way, that does not involve a UITextView or 3rd party framework, to make multiple tappable links, on a label. A side note, with the string, for the label is, it’s fetched from a server, so we don’t know the links ahead of time.

As an example, lets say there’s a post, and it has two links, each to a random site dynamically fetched from the server. After detecting that they are links, which I can do, how would I make those tappable?

I have scoured StackOverflow, there have been no duplicates or this question, that I can find. If you find something exactly like this question, feel free to mark it as a duplicate. All I’ve seen were people recommending to use a UITextView, a 3rd party framework, or to use attributed strings, but the links are known at that point, they aren’t dynamically fetched.

Upvotes: 0

Views: 804

Answers (2)

Michael
Michael

Reputation: 303

As @DonMag pointed out, in the comments of the question - I could in fact use a UITextView, and disabling scrolling, which fixed the original reason I was having, that made me turn to do it with a UILabel.

Upvotes: 1

Blazej SLEBODA
Blazej SLEBODA

Reputation: 9915

If you would like to do it with a UILabel class then:

  • set 'isUserInteractionEnabled' property to true
  • create a Tap Gesture Recogniser and assign it to the gesture recognisers collection outlet of the label
  • write 'IBAction func didTapLink(_ sender: Any)' which opens a selected link and connect is with the tap gesture recogniser 'sent action selector' outlet
  • set 'text' property with a link

if you must to display a link as in a browser then:

  • set 'attributedText' property with a link
  • add 'NSAttributedString.Key.link' attribute to the link range

Upvotes: 0

Related Questions