How to make custom toggle in SwiftUI

Issue #676

I’ve used the default SwiftUI to achieve the 2 tab views in SwiftUI. It adds a default box around the content and also opinionated paddings. For now on light mode on macOS, the unselected tab has wrong colors.

The way to solve this is to come up with a custom toggle, that we can style and align the way we want. Here is how I did for my app Push Hero

Using a Text instead of Button here gives me default static text look.

Screenshot 2020-09-29 at 06 52 33
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
struct AuthenticationView: View {
@Binding var input: Input

var body: some View {
toggle
}

var toggle: some View {
VStack(alignment: .leading) {
HStack {
HStack(spacing: 0) {
Text("🔑 Key")
.style(selected: input.authentication == .key)
.onTapGesture {
self.input.authentication = .key
}

Text("📰 Certificate")
.style(selected: input.authentication == .certificate)
.onTapGesture {
self.input.authentication = .certificate
}
}
.padding(3)
.background(Color.white.opacity(0.2))
.cornerRadius(6)

Spacer()
}

choose
Spacer()
}
}

var choose: AnyView {
switch input.authentication {
case .key:
return KeyAuthenticationView().erase()
case .certificate:
return CertificateAuthenticationView().erase()
}
}
}

private extension Text {
func style(selected: Bool) -> some View {
return self
.padding(.vertical, 3)
.padding(.horizontal, 4)
.background(selected ? Color.white.opacity(0.5) : Color.clear)
.cornerRadius(6)
}
}

Comments