How can I create a "hyperlink" using Swift?
I am trying to make individual pieces of text UILabel
clickable. What I'm looking for is commonly referred to 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 tag a
is its own UILabel
, and ideally it will open Safari to the specified href
tag when you click on the text between tags.
I've found many resources on how to do this in Objective-C, but they all seem overly complicated and don't translate well to Swift (they fit the Objective-C organizational structure which doesn't work) t works well in Swift and goes against the recommended way of using the language).
Here are a few:
- How to add a hyperlink to an iPhone app?
- How to make clickable link inside NSTextField and Cocoa
- Text as a hyperlink in Objective-C
If I had 3 UILabel
s,
Paragraph 1
Point 2
Point 3
then what would be the best "Swift-y" way to make each element open to a different url in Safari?
I could create separate buttons for each, but UILabel
programmatically populated, so I thought that making the text respond to taps might be the best option.
source to share
One approach would be something like this:
Assumptions:
- self.urls is a string array containing the URLs associated with each
UILabel
. - Each is
UILabel
tag
assigned a corresponding index in the array -
labelTapped:
installed as a handlertouchUpInside
for 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); } }
source to share
Swift 3 I created a LinkUILabel class in github: https://github.com/jorgecsan/LinkUILabel With this, you only need to add the url, which can be checked as the image is displayed: or assign the url variable programmatically:
linkUILabel.url = "www.example.com"
If you want to realize yourself on your own, I found this solution! :)
through:
// 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 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! :)
source to share