-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectableButton.swift
More file actions
93 lines (74 loc) · 2.37 KB
/
SelectableButton.swift
File metadata and controls
93 lines (74 loc) · 2.37 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//
// SelectableButton.swift
// Calie
//
// Created by Mac mini on 2022/05/07.
// Copyright © 2022 Mac mini. All rights reserved.
//
import UIKit
import Then
class SelectableButton: UIButton, Identifiable { // has id
var id = UUID()
var title: String
public var isSelected_: Bool {
get {
return self.isSelected
}
set {
self.isSelected = newValue
}
}
init(title: String, frame: CGRect = .zero) {
self.title = title
super.init(frame: frame)
setupInitialColor()
}
public func setupInitialColor() {
self.backgroundColor = .black
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//class SelectableButtonGroup: UIView {
class SelectableButtonStackView: UIStackView {
func addArrangedButton(_ btn: SelectableButton) {
super.addArrangedSubview(btn)
buttons.append(btn)
}
public var buttons: [SelectableButton] = []
public var selectedBtnIndex: Int?
private var selectedColor: UIColor
private var defaultColor: UIColor
private var prevPressedBtnId: UUID?
private var currentPressedBtnId: UUID?
public func buttonSelected(_ id: UUID) {
prevPressedBtnId = currentPressedBtnId // both can be nil for the first selection
for (index, button ) in buttons.enumerated() {
if button.id == id {
currentPressedBtnId = id
selectedBtnIndex = index
button.backgroundColor = selectedColor
} else if let validPrev = prevPressedBtnId,
validPrev == button.id {
button.backgroundColor = defaultColor
}
}
}
private func setupInitialColor(){
for eachBtn in buttons {
eachBtn.setupInitialColor()
}
}
init(selectedColor: UIColor = .gray, defaultColor: UIColor = .black, spacing: CGFloat = 10, frame: CGRect = .zero) {
self.selectedColor = selectedColor
self.defaultColor = defaultColor
super.init(frame: frame)
setupInitialColor()
self.distribution = .fillEqually
self.spacing = spacing
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}