Skip to content
Khoa Pham@onmyway133

How to make custom toggle in SwiftUI

1 min read

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
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)
    }
}

Keep reading

Type to search titles and full text.

↑ ↓ move↵ openPagefind