Created
April 18, 2020 13:43
-
-
Save martinhoeller/c4372ec33b4352115f34d92b359286aa to your computer and use it in GitHub Desktop.
An NSTextView subclass that automatically highlights links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AppKit | |
// based on https://www.hackingwithswift.com/example-code/strings/how-to-detect-a-url-in-a-string-using-nsdatadetector | |
// and https://stackoverflow.com/a/14604456/379776 | |
class LinkDetectingTextView: NSTextView { | |
override var string: String { | |
didSet { | |
highlightLinks() | |
} | |
} | |
private func highlightLinks() { | |
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return } | |
let matches = detector.matches(in: string, options: [], range: NSRange(location: 0, length: string.count)) | |
for match in matches { | |
guard let url = match.url else { continue } | |
let linkAttributes = [NSAttributedString.Key.link: url] | |
textStorage?.addAttributes(linkAttributes, range: match.range) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment