NEW! Master Swift design patterns with my latest book! >>

How to make tappable links in NSAttributedString

Paul Hudson       @twostraws

You can make tappable hyperlinks in any attributed string, which in turn means you can add tappable hyperlinks to any UIKit control. If you're working with UITextView (which is likely, let's face it), you get basic tappable hyperlink just by enabling the "Links" data detector in Interface Builder, but that doesn't work for arbitrary strings – for example, maybe you want the word "click here" to tappable.

Below is a complete example of arbitrary tappable hyperlinks using a UITextView. Make sure your text view has "Selectable" enabled, as this is required by iOS:

class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet var textView: UITextView!

    override func viewDidLoad() {
        let attributedString = NSMutableAttributedString(string: "Want to learn iOS? You should visit the best source of free iOS tutorials!")
        attributedString.addAttribute(.link, value: "https://www.hackingwithswift.com", range: NSRange(location: 19, length: 55))

        textView.attributedText = attributedString
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        UIApplication.shared.open(URL, options: [:])
        return false
    }
}

There are two important things to note about this technique.

First, the tap cannot be very brief, which means quick taps are ignored by iOS. If you find find this annoying you might consider something like this: https://gist.github.com/benjaminbojko/c92ac19fe4db3302bd28.

Second, this technique is easily used with custom URL schemes, e.g. yourapp://, which you can catch and parse inside shouldInteractWith to trigger your own behaviors.

Available from iOS 6.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Get my latest video for free

Learn about value types, functional programming, and protocol-oriented programming in this new video – it's free!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 3.5/5

Click here to visit the Hacking with Swift store >>