-
Notifications
You must be signed in to change notification settings - Fork 12
/
MoCode.swift
60 lines (43 loc) · 1.5 KB
/
MoCode.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
// Created by Sanjay Madan on May 26, 2015
// Copyright (c) 2015 mowglii.com
import Cocoa
// MARK: - MoView
// MoView is an Auto Layout-ready view that makes custom
// drawing possible without the need to subclass.
class MoView: NSView {
// Optional background color.
var bgColor: NSColor? {
didSet {
needsDisplay = true
}
}
// Optional draw block allows custom drawing without subclassing.
// The block is passed the current context and the view bounds.
var drawBlock: ((_ context: CGContext, _ bounds: NSRect) -> Void)? {
didSet {
needsDisplay = true
}
}
// By default, do not translate autoresizing mask into constraints
// so doing Auto Layout in code is a little more efficient.
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.translatesAutoresizingMaskIntoConstraints = false
}
override func draw(_ dirtyRect: NSRect) {
// Fill with optional background color.
if let color = bgColor {
color.set()
bounds.fill(using: .sourceOver)
}
// Draw with optional draw block.
if let block = drawBlock {
let context = NSGraphicsContext.current!.cgContext
block(context, bounds)
}
super.draw(dirtyRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}