Skip to content

Instantly share code, notes, and snippets.

@KevinGutowski
Created January 12, 2021 09:49
Show Gist options
  • Save KevinGutowski/9737b99cdff75e3f8aaefd1fc32fd07b to your computer and use it in GitHub Desktop.
Save KevinGutowski/9737b99cdff75e3f8aaefd1fc32fd07b to your computer and use it in GitHub Desktop.
Make NSTextFIeld clickable and take you to a URL
//
// LinkLabel.swift
// TestText
//
// Created by Kevin Gutowski on 1/12/21.
//
import Cocoa
@IBDesignable
class LinkLabel: NSTextField {
@IBInspectable var url: String = ""
@IBInspectable var hideUnderline: Bool = false
override func resetCursorRects() {
discardCursorRects()
addCursorRect(self.bounds, cursor: NSCursor.pointingHand)
}
override func awakeFromNib() {
super.awakeFromNib()
self.allowsEditingTextAttributes = true
self.isSelectable = true
let mutableAttrString = NSMutableAttributedString(attributedString: attributedStringValue)
let urlAttributes: [NSAttributedString.Key:Any] = [.link: NSURL(string: url)!,
.foregroundColor: NSColor.linkColor]
mutableAttrString.addAttributes(urlAttributes, range: NSMakeRange(0, stringValue.count))
if hideUnderline {
mutableAttrString.addAttribute(.underlineColor, value: NSColor.init(calibratedRed: 0, green: 0, blue: 0, alpha: 0), range: NSMakeRange(0, stringValue.count))
}
attributedStringValue = mutableAttrString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment