|
import AppKit |
|
public class FlatButton: NSButton { |
|
|
|
public var buttonColor: NSColor = NSColor(calibratedRed: 0.201, green: 0.404, blue: 0.192, alpha: 1) |
|
public var onClickColor: NSColor = NSColor(calibratedRed: 0.304, green: 0.601, blue: 0.294, alpha: 1) |
|
public var textColor: NSColor = NSColor.white |
|
|
|
public override func draw(_ dirtyRect: NSRect) { |
|
super.draw(dirtyRect) |
|
|
|
let rectanglePath = NSBezierPath(rect: NSRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) |
|
|
|
var fillColor: NSColor |
|
var strokeColor: NSColor |
|
|
|
rectanglePath.fill() |
|
|
|
if self.isHighlighted { |
|
strokeColor = self.buttonColor |
|
fillColor = self.onClickColor |
|
} else { |
|
strokeColor = self.onClickColor |
|
fillColor = self.buttonColor |
|
} |
|
|
|
strokeColor.setStroke() |
|
rectanglePath.lineWidth = 5 |
|
rectanglePath.stroke() |
|
fillColor.setFill() |
|
rectanglePath.fill() |
|
bezelStyle = .shadowlessSquare |
|
|
|
let textRect = NSRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) |
|
let textTextContent = self.title |
|
let textStyle = NSMutableParagraphStyle() |
|
textStyle.alignment = .center |
|
|
|
let textFontAttributes : [ NSAttributedString.Key : Any ] = [ |
|
.font: NSFont(name: "SFUIText-Medium", size: NSFont.systemFontSize)!, |
|
.foregroundColor: textColor, |
|
.paragraphStyle: textStyle |
|
] |
|
|
|
let textTextHeight: CGFloat = textTextContent.boundingRect(with: NSSize(width: textRect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: textFontAttributes).height |
|
let textTextRect: NSRect = NSRect(x: 0, y: -3 + ((textRect.height - textTextHeight) / 2), width: textRect.width, height: textTextHeight) |
|
NSGraphicsContext.saveGraphicsState() |
|
textTextContent.draw(in: textTextRect.offsetBy(dx: 0, dy: 3), withAttributes: textFontAttributes) |
|
NSGraphicsContext.restoreGraphicsState() |
|
} |
|
} |
I deleted the comment because I found some time to update the code anyway. I would just recommend reading the documentation provided by Apple. The HIG is the go to resource for that.
https://developer.apple.com/design/human-interface-guidelines/macos/overview/themes/
I would recommend StackOverflow for specific questions.
Even SwiftUI is in it's infancy and has a lot of bugs and frustrating constraints, the power of coding the same "language" for all devices across the Apple ecosystem is a real plus. I say "language", because the difference between iOS, tvOS, macOS and watchOS for that sake, is so far from each other that it's almost like different dialects of the same language. So for better or worse, I went all inn for SwiftUI.