How can I create a "hyperlink" with Swift?
Solution 1
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 thetouchUpInside
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);
}
}
Solution 2
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: 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!:)
Solution 3
Hyperlink via UITextView
var termsConditionsTextView: UITextView = {
let view = UITextView()
view.backgroundColor = .clear
view.textAlignment = .left
let firstTitleString = "By registering for THIS_APP I agree with the "
let secondTitleString = "Terms & Conditions"
let finishTitleString = firstTitleString + secondTitleString
let attributedString = NSMutableAttributedString(string: finishTitleString)
attributedString.addAttribute(.link, value: "https://stackoverflow.com", range: NSRange(location: firstTitleString.count, length: secondTitleString.count))
view.attributedText = attributedString
view.textContainerInset = .zero
view.linkTextAttributes = [
.foregroundColor: UIColor.blue,
.underlineStyle: NSUnderlineStyle.single.isEmpty
]
view.font = view.font = UIFont(name: "YOUR_FONT_NAME", size: 16)
view.textColor = UIColor.black
return view }()
Comments
-
AstroCB over 3 years
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 ownUILabel
, and it would ideally open Safari to the specifiedhref
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
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. -
Tim Quinn over 9 yearsLooks to me like you have duplicated the function of a button.
-
Tim Quinn over 9 yearsThen I would have to ask, out of curiosity, why? A button is just a piece of text that calls an action when you tap it. That is exactly what you are asking for.
-
AstroCB over 9 years@TimQuinn The problem here was more opening Safari than it was calling the action: these are
UILabel
s and that is why I asked for a solution using them. I could use a button, but why change it if the only difference is adding a touchup handler to the label? -
AstroCB about 9 years@TimQuinn I actually did end up making them buttons because the way they're handled natively is more suited to it than the way
UILabel
s are. I was hesitant to do so originally because my intent was to have something resembling a list, but the buttons were similar enough to the labels to work out.