forked from HabitRPG/habitica-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHabiticaButton.swift
88 lines (75 loc) · 2.45 KB
/
HabiticaButton.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//
// HabiticaButton.swift
// Habitica
//
// Created by Phillip Thelen on 02.11.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import UIKit
@IBDesignable
class HabiticaButton: UIButton {
@IBInspectable public var buttonColor: UIColor = UIColor.purple200 {
didSet {
backgroundColor = buttonColor
updateLegibility()
}
}
override func setTitleColor(_ color: UIColor?, for state: UIControl.State) {
super.setTitleColor(color, for: state)
updateLegibility()
}
override open var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? buttonColor.lighter(by: 15) : buttonColor
}
}
override open var isSelected: Bool {
didSet {
backgroundColor = isHighlighted ? buttonColor.lighter(by: 25) : buttonColor
}
}
override open var isEnabled: Bool {
didSet {
backgroundColor = isEnabled ? buttonColor : UIColor.gray400
}
}
override open var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
func setupView() {
cornerRadius = 12
setTitleColor(.white, for: .normal)
isPointerInteractionEnabled = true
}
private func updateLegibility() {
// Calling super here since we don't want to accidentally create an infinite recursion
if (backgroundColor?.difference(between: currentTitleColor) ?? 1.0) < 1.0 {
if backgroundColor?.isLight() == true {
if currentTitleColor.brightness > 0.9 {
super.setTitleColor(ThemeService.shared.theme.primaryTextColor, for: .normal)
} else {
super.setTitleColor(ThemeService.shared.theme.backgroundTintColor, for: .normal)
}
} else {
if currentTitleColor.brightness < 0.2 {
super.setTitleColor(ThemeService.shared.theme.lightTextColor, for: .normal)
} else {
super.setTitleColor(currentTitleColor.lighter(by: 10), for: .normal)
}
}
}
}
}