AstroCB AstroCB - 2 months ago 26
Swift Question

How can I create a "hyperlink" with Swift?

I'm trying to make separate pieces of text

UILabel
s 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:



If I had a 3
UILabel
s,


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
UILabel
s are programmatically populated, so I was thinking that making the text respond to taps might be a better option.

Answer

The One approach would be something like the following.
The assumptions are:

  • self.urls is a string array containing the urls associated with each UILabel.
  • Each UILabel tag has been set to the corresponding index in the array
  • labelTapped: is set as the touchUpInside handler for the labels.
import Foundation
import UIKit

class urltest {

    var urls:[String]

    init() {
        self.urls=[String]()  // Load URLs into here
    }

    @IBAction func labelTapped(sender:UILabel!) {

        let urlIndex=sender.tag;
        if (urlIndex >= 0 && urlIndex < self.urls.count) {
           self.openUrl(self.urls[urlIndex]);
        }

    }

    func openUrl(url:String!) {

        let targetURL=NSURL.URLWithString(url)

        let application=UIApplication.sharedApplication()

        application.openURL(targetURL);

    }
}