How to properly do buttons in table view cells using Swift closures
Note: This post is an upgrade of the original post…
If you’ve encountered a use case where you need a tappable link in a label, you might have been a bit confused. See, UILabels do not natively support tappable links.
Luckily, there are at least two workarounds at your service:
You might think it’s an overkill to use a UITextView instead of a UILabel. In some cases, you might be right, but depending on your needs, this might be a completely viable solution.
To make it work, you need this short snippet of code (assuming you already have a UITextView hooked up with a IBOutlet in your View Controller):
let plainString = "I ❤️ Candy Code"
let attributedString = NSMutableAttributedString(string: plainString)
let range = (plainString as NSString).rangeOfString("Candy Code")
// Important: if you want to open other URLs, not only http, it's important to set a NSURL here, not just a String
attributedString.addAttributes([NSLinkAttributeName: NSURL(string: "http://www.candycode.io/")!], range: range)
// Optional: let's set a bigger font
attributedString.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(18)], range: NSMakeRange(0, attributedString.length))
textView.attributedText = attributedString
// Important: Unless you want your users to see a keyboard, set the editable property to false
textView.editable = false
This is it! The Candy Code will open Safari and show this lovely website. 🙂
For the full working sample, click here.
The second workaround is …
Like I mentioned above – it depends on your situation, but I dislike adding dependencies for just one use case. If you have to support links in multiple places in your app, by all means use this library. If you only need it in one place, seriously consider replacing your UILabel with a UITextView and focus on more important issues!
Here’s a link to the TTTAttributedLabel repo.
Take part in the 5-day course with actionable tasks that will let you become a master at recognizing and solving the most common mistakes iOS developers do with Auto Layout.
Let Auto Layout become a tool you swing with your utmost confidence!