Skip to content

Instantly share code, notes, and snippets.

@martinhoeller
Created April 18, 2020 13:43
Show Gist options
  • Save martinhoeller/c4372ec33b4352115f34d92b359286aa to your computer and use it in GitHub Desktop.
Save martinhoeller/c4372ec33b4352115f34d92b359286aa to your computer and use it in GitHub Desktop.
An NSTextView subclass that automatically highlights links
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