|
|
|
|
|
import Cocoa |
|
import AppKit |
|
|
|
protocol MWPButtonDelegate: AnyObject { |
|
func userDidClickedtButton(sender: MWPButton) |
|
} |
|
|
|
@IBDesignable |
|
class MWPButton: NSView { |
|
|
|
@IBInspectable |
|
public var backgroundColor: NSColor = .white |
|
|
|
@IBInspectable |
|
public var backgroundDisabledColor: NSColor = .white |
|
|
|
@IBInspectable |
|
public var titleButton: String = "Button" { |
|
didSet { |
|
self.needsDisplay = true |
|
} |
|
} |
|
|
|
@IBInspectable |
|
public var fontSize: CGFloat = 12.0 |
|
|
|
@IBInspectable |
|
public var titleYPosition: CGFloat = 9.0 |
|
|
|
@IBInspectable |
|
public var cornerRadius: CGFloat = 0.0 |
|
|
|
@IBInspectable |
|
public var titleColor: NSColor = .white |
|
|
|
@IBInspectable |
|
public var titleDisabledColor: NSColor = .white |
|
|
|
@IBInspectable |
|
public var isEnabled: Bool = true { |
|
didSet { |
|
self.needsDisplay = true |
|
} |
|
} |
|
|
|
@IBInspectable |
|
public var borderWidth: CGFloat = 0 |
|
|
|
@IBInspectable |
|
public var borderColor: NSColor = .clear |
|
|
|
@IBInspectable |
|
public var buttonTag: Int = 0 |
|
|
|
weak var buttonDelegate: MWPButtonDelegate? |
|
|
|
override open func draw(_ dirtyRect: NSRect) { |
|
super.draw(dirtyRect) |
|
|
|
let path = NSBezierPath(roundedRect: self.bounds, xRadius: cornerRadius, yRadius: cornerRadius) |
|
isEnabled ? backgroundColor.setFill() : backgroundDisabledColor.setFill() |
|
path.fill() |
|
path.addClip() |
|
|
|
if borderWidth > 0 { |
|
let borderPath = NSBezierPath(roundedRect: self.bounds, xRadius: cornerRadius, yRadius: cornerRadius) |
|
isEnabled ? borderColor.setStroke() : borderColor.withAlphaComponent(0.4).setStroke() |
|
borderPath.lineWidth = borderWidth |
|
borderPath.stroke() |
|
} |
|
|
|
let textRect = NSRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) |
|
let textTextContent = titleButton |
|
let textStyle = NSMutableParagraphStyle() |
|
textStyle.alignment = .center |
|
let textFontAttributes = [NSAttributedString.Key.font: NSFont.systemFont(ofSize: fontSize, weight: .semibold), NSAttributedString.Key.foregroundColor: isEnabled ? titleColor : titleDisabledColor, NSAttributedString.Key.paragraphStyle: textStyle] |
|
|
|
let textTextHeight: CGFloat = textTextContent.boundingRect(with: NSSize(width: textRect.width, height: CGFloat.infinity), options: NSString.DrawingOptions.usesLineFragmentOrigin, attributes: textFontAttributes).height |
|
|
|
let textTextRect: NSRect = NSRect(x: 0, y:titleYPosition, width: textRect.width, height: textTextHeight) |
|
NSGraphicsContext.saveGraphicsState() |
|
textRect.clip() |
|
textTextContent.draw(in: textTextRect.offsetBy(dx: 0, dy: 0), withAttributes: textFontAttributes) |
|
NSGraphicsContext.restoreGraphicsState() |
|
} |
|
|
|
override open func mouseDown(with event: NSEvent) { |
|
if event.clickCount == 1 { |
|
buttonDelegate?.userDidClickedtButton(sender: self) |
|
} |
|
} |
|
} |