-
Notifications
You must be signed in to change notification settings - Fork 1
/
DudNSButton.swift
70 lines (60 loc) · 2.31 KB
/
DudNSButton.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
// DudNSButton.swift
//
// Created by Philip Fung on 4/11/17.
//
// Usage:
//
// let buttonView = DudNSButton.init(frame: NSRect(x: 0, y: 0, width: 300.0, height: 150.0))
// buttonView.setBackgroundColor(color: NSColor.blue)
// buttonView.setBorderAttributes(color: NSColor.black, borderWidth: 2.0, cornerRadius: 5.0)
// buttonView.setText(text: "Submit", font: NSFont.boldSystemFont(ofSize: 16.0), color: NSColor.white)
//
// MIT License
import Cocoa
import Foundation
class DudNSButton: NSButton {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self._commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self._commonInit()
}
func setBackgroundColor(color: NSColor) {
self.image = self._createBackgroundImage(color: color)
}
func setText(text: String, font: NSFont, color: NSColor) {
let paragraphStyle = NSMutableParagraphStyle.init()
paragraphStyle.alignment = .center
let range = NSRange.init(location: 0, length: (text.lengthOfBytes(using: String.Encoding.utf8)))
let attributedTitle = NSMutableAttributedString.init(string: text)
attributedTitle.addAttribute( NSParagraphStyleAttributeName, value: paragraphStyle, range: range)
attributedTitle.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
attributedTitle.addAttribute(NSFontAttributeName, value: font, range: range)
self.attributedTitle = attributedTitle
}
func setBorderAttributes(color: NSColor,
borderWidth: CGFloat,
cornerRadius: CGFloat) {
self.isBordered = true
self.layer?.masksToBounds = true
self.layer?.borderColor = color.cgColor
self.layer?.borderWidth = borderWidth
self.layer?.cornerRadius = cornerRadius
}
private func _commonInit() {
self.cell = NSButtonCell()
self.wantsLayer = true
}
private func _createBackgroundImage(color: NSColor)->NSImage {
let size = self.frame.size
let image = NSImage(size: size)
image.lockFocus()
let rect = NSMakeRect(0, 0, size.width, size.height)
color.drawSwatch(in: rect)
image.unlockFocus()
return image
}
}