Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a "hyperlink" with Swift?

I'm trying to make separate pieces of text UILabels clickable. What I'm looking for is commonly known as a hyperlink in web development.

<a href="//example.com">Link 1</a>
<a href="//example.com/example">Link 2</a>
<a href="//example.com/other_example">Link 3</a>

Each a tag is its own UILabel, and it would ideally open Safari to the specified href when the text between the tags is clicked.

I've found a bevy of resources on how to do this sort of thing in Objective-C, but they all seem unnecessarily complicated and don't translate well to Swift (they fit an Objective-C organizational structure that doesn't work well in Swift and goes against the recommended way of using the language).

Here are a few:

  • How to add hyperlink in iPhone app?
  • How to make a clickable link inside a NSTextField and Cocoa
  • Text as Hyperlink in Objective-C

If I had a 3 UILabels,

Item 1

Item 2

Item 3

then what would be the best "Swift-y" way to make each item open to a different URL in Safari?

I could create separate buttons for each, but the UILabels are programmatically populated, so I was thinking that making the text respond to taps might be a better option.

like image 408
AstroCB Avatar asked Oct 21 '25 05:10

AstroCB


1 Answers

Swift 3 I created a LinkUILabel class in github: https://github.com/jorgecsan/LinkUILabel With this you only need add the url inspectable as the shows the image: Example label with url or assign the url variable programmatically:

linkUILabel.url = "www.example.com"

If you want to implement by your self also I found that solution!:)

using:

// This is the label
@IBOutlet weak var label: UILabel!

override func loadView() {
    super.loadView()

    // This is the key
    let tap = UITapGestureRecognizer(target: self, action: #selector(self.onClicLabel(sender:)))
    label.isUserInteractionEnabled = true
    label.addGestureRecognizer(tap)
}

// And that's the function :)
func onClicLabel(sender:UITapGestureRecognizer) {
    openUrl("http://www.google.com")
}


func openUrl(urlString:String!) {
    let url = URL(string: urlString)!
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(url)
    }
}

Hope it helps!:)

like image 93
Jorge Cordero Avatar answered Oct 23 '25 17:10

Jorge Cordero