AstroCB AstroCB - 5 months ago 43
Swift Question

How can I create a "hyperlink" with Swift?

I'm trying to make separate pieces of text

s clickable. What I'm looking for is commonly known as a hyperlink in web development.

<a href="//">Link 1</a>
<a href="//">Link 2</a>
<a href="//">Link 3</a>

tag is its own
, and it would ideally open Safari to the specified
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

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


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) {


    func openUrl(url:String!) {

        let targetURL=NSURL.URLWithString(url)

        let application=UIApplication.sharedApplication()