Skip to content

Instantly share code, notes, and snippets.

@thecoolwinter
Last active June 4, 2024 15:07
Show Gist options
  • Save thecoolwinter/993d898b6aa555511a5ad4a0a2fb3ef9 to your computer and use it in GitHub Desktop.
Save thecoolwinter/993d898b6aa555511a5ad4a0a2fb3ef9 to your computer and use it in GitHub Desktop.
Quick dirty NSLabel class for drawing text.
//
// NSLabel.swift
//
//
// Created by Khan Winter on 4/8/22.
//
import AppKit
class NSLabel: NSView {
var string: String
var font: NSFont
var backgroundColor: NSColor?
override init(frame frameRect: NSRect) {
self.string = ""
self.font = NSFont.systemFont(ofSize: 12, weight: .regular)
super.init(frame: frameRect)
}
init(string: String) {
self.string = string
self.font = NSFont.systemFont(ofSize: 12, weight: .regular)
super.init(frame: .zero)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var intrinsicContentSize: NSSize {
makeAttributedString().size()
}
override func draw(_ dirtyRect: NSRect) {
guard let context = NSGraphicsContext.current?.cgContext else { return }
context.saveGState()
if let backgroundColor {
context.setFillColor(backgroundColor.cgColor)
context.fill([NSRect(origin: .zero, size: self.frame.size)])
}
let attributedString = makeAttributedString()
let size = attributedString.size()
let yPos = (self.frame.size.height - size.height)/2
let rect = NSRect(x: 0, y: yPos, width: self.frame.size.width, height: size.height)
attributedString.draw(in: rect)
context.restoreGState()
}
private func makeAttributedString() -> NSAttributedString {
// swiftlint:disable:next force_cast
let paragraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byTruncatingTail
return NSAttributedString(
string: string,
attributes: [.font: font, .paragraphStyle: paragraphStyle]
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment