-
Notifications
You must be signed in to change notification settings - Fork 5
/
Badge.swift
92 lines (80 loc) · 2.33 KB
/
Badge.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
89
90
91
92
//
// Badge.swift
//
// Made with ❤️ by Novum
//
// Copyright © Telefonica. All rights reserved.
//
import SwiftUI
private enum Constants {
static let maximumValue = 9
static let flagBadgeSize: CGFloat = 8
static let numericBadgeSize: CGFloat = 20
static let numericBadgeLargeSize: CGFloat = 28
static let horizontalInset: CGFloat = 2
}
public struct Badge: View {
public enum Style {
case numeric(Int)
case flag
}
private let style: Style
public init(style: Style) {
self.style = style
}
public var body: some View {
switch style {
case .numeric(let number):
numericView(number)
case .flag:
Rectangle()
.fill(Color.badge)
.round(radiusStyle: .indicator)
.frame(width: Constants.flagBadgeSize, height: Constants.flagBadgeSize)
}
}
@ViewBuilder
private func numericView(_ number: Int) -> some View {
ZStack {
if number > Constants.maximumValue {
Rectangle().fill(Color.badge)
.round(radiusStyle: .indicator)
label("+\(Constants.maximumValue)")
} else {
Rectangle().fill(Color.badge)
.round(radiusStyle: .indicator)
label("\(number)")
}
}
.frame(
width: number > Constants.maximumValue ? Constants.numericBadgeLargeSize : Constants.numericBadgeSize,
height: Constants.numericBadgeSize
)
}
@ViewBuilder
private func label(_ text: String) -> some View {
Text(text)
.font(.textPreset1(weight: .indicator, constrainedToPreferredSize: .accessibilityMedium))
.foregroundColor(.textPrimaryInverse)
}
}
#if DEBUG
struct Badge_Previews: PreviewProvider {
static var previews: some View {
Preview {
VStack {
HStack {
ForEach(0 ..< 11) { _ in
Badge(style: .flag)
}
}
HStack {
ForEach(0 ..< 11) {
Badge(style: .numeric($0))
}
}
}
}
}
}
#endif