-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathMixedStateCheckbox.swift
More file actions
78 lines (64 loc) · 1.97 KB
/
MixedStateCheckbox.swift
File metadata and controls
78 lines (64 loc) · 1.97 KB
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
70
71
72
73
74
75
76
77
78
import SwiftUI
import AppKit
public enum CheckboxMixedState {
case off, mixed, on
}
public struct MixedStateCheckbox: View {
let title: String
let font: NSFont
let action: () -> Void
@Binding var state: CheckboxMixedState
public init(title: String, font: NSFont, state: Binding<CheckboxMixedState>, action: @escaping () -> Void) {
self.title = title
self.font = font
self.action = action
self._state = state
}
public var body: some View {
MixedStateCheckboxView(title: title, font: font, state: state, action: action)
}
}
private struct MixedStateCheckboxView: NSViewRepresentable {
let title: String
let font: NSFont
let state: CheckboxMixedState
let action: () -> Void
func makeNSView(context: Context) -> NSButton {
let button = NSButton()
button.setButtonType(.switch)
button.allowsMixedState = true
button.title = title
button.font = font
button.target = context.coordinator
button.action = #selector(Coordinator.onButtonClicked)
button.setContentHuggingPriority(.required, for: .horizontal)
button.setContentCompressionResistancePriority(.required, for: .horizontal)
return button
}
func makeCoordinator() -> Coordinator {
Coordinator(action: action)
}
class Coordinator: NSObject {
let action: () -> Void
init(action: @escaping () -> Void) {
self.action = action
}
@objc func onButtonClicked() {
action()
}
}
func updateNSView(_ nsView: NSButton, context: Context) {
if nsView.font != font {
nsView.font = font
}
nsView.title = title
switch state {
case .off:
nsView.state = .off
case .mixed:
nsView.state = .mixed
case .on:
nsView.state = .on
}
}
}