2

I have a label that says "click here". When the user taps "here" I want it to take my user to https://www.google.com. How do I do this? Thanks in advance!

Trev347
  • 318
  • 1
  • 12
  • I forgot to add this, but I am doing this programmatically, not using storyboard. – Trev347 Nov 26 '21 at 04:24
  • if that's not possible then how do apps like instagram say at the bottom of the screen "By creating an account you agree to our terms of service and privacy policy" with a link to both the terms of service and privacy policy? – Trev347 Nov 26 '21 at 04:41
  • 1
    As Satheesh suggests, they must be either using `UITapGesture` for the whole text segment or `UITextView` for a partial text segment. If necessary, ask the Instagram company or whoever it is. – El Tomato Nov 26 '21 at 04:56
  • Does this answer your question? [Create tap-able "links" in the NSAttributedString of a UILabel?](https://stackoverflow.com/questions/1256887/create-tap-able-links-in-the-nsattributedstring-of-a-uilabel) – aheze Nov 26 '21 at 05:08

1 Answers1

2

Two ways to do it.

  1. Tap gesture - UITapGestureRecognizer
// considering you have a UILabel is added to your screen and you have formatted the label to look like a link.
let labelTap = UITapGestureRecognizer(target: self, action: #selector(self.linkLabelTapped(_:)))
self.linkLabel.isUserInteractionEnabled = true
self.linkLabel.addGestureRecognizer(labelTap)


@objc func linkLabelTapped(_ sender: UITapGestureRecognizer) {
    print("linkLabelTapped")
}
  1. Don't use UILabel but UITextView with link recognition which gives you the formatting by default.
linkTextView.userInteractionEnabled = true
linkTextView.selectable = true
linkTextView.dataDetectorTypes = .Link
linkTextView.text = "https://www.google.com."
linkTextView.isEditable = false
Satheesh
  • 10,998
  • 6
  • 50
  • 93