Posts in "Swift"

How to hyperlink part of a text in a UITextView – Swift

Unless a url is spelled out in a UITextView, there isn’t a simple way to make it linkable in Interface Builder. So if you want to make some text hyperlinked like that, you’ll need to do a few maneuvers in code. The simplest way I found so far is this one, which I’ve adopted and updated for swift 4 and UITextView in particular. You can extend NSMutableAttributedString to find and hyperlink part of the text. Add this in a dedicated Extensions swift file in your project: extension NSMutableAttributedString { public func setAsLink(textToFind:String, linkURL:String) -> Bool { let foundRange = self.mutableString.range(of: textToFind) if foundRange.location != NSNotFound { self.addAttribute(.link, value: linkURL, range: foundRange) return true } return false } } Then where you have your textView defined, you copy the text to a NSMutableAttributedString, use the setAsLink method on it, which returns true if successful, and use that to copy the linked text back to the textView: let linkedText = NSMutableAttributedString(attributedString: myTextView.attributedText) let hyperlinked = linkedText.setAsLink(textToFind: "this part of the text will be hyperlinked", linkURL: "https://www.website.com/") if hyperlinked { myTextView.attributedText = NSAttributedString(attributedString: linkedText) }