Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Custom Toggle Switch #339

Open
platojobs opened this issue Jun 28, 2024 · 0 comments
Open

Custom Toggle Switch #339

platojobs opened this issue Jun 28, 2024 · 0 comments
Labels
MobileDevelopment iOS、安卓、Flutter、go

Comments

@platojobs
Copy link
Owner

import SwiftUI

struct CustomToggle: View {
    @Binding var isOn: Bool
    var onColor: Color = .green
    var offColor: Color = .red

    var body: some View {
        HStack {
            RoundedRectangle(cornerRadius: 16)
                .fill(isOn ? onColor : offColor)
                .frame(width: 50, height: 30)
                .overlay(
                    Circle()
                        .fill(Color.white)
                        .frame(width: 24, height: 24)
                        .offset(x: isOn ? 10 : -10)
                        .animation(.default, value: isOn)
                )
                .onTapGesture {
                    isOn.toggle()
                }
            Text(isOn ? "ON" : "OFF")
                .font(.headline)
                .padding(.leading, 10)
        }
        .padding()
    }
}

struct CustomToggle_Previews: View {
    @State private var isOn = true

    var body: some View {
        Group {
            CustomToggle(isOn: $isOn)
                .previewDisplayName("ON State")

            CustomToggle(isOn: .constant(false))
                .previewDisplayName("OFF State")
        }
    }
}

#Preview {
    CustomToggle_Previews()
}
@platojobs platojobs added the MobileDevelopment iOS、安卓、Flutter、go label Jun 28, 2024
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
MobileDevelopment iOS、安卓、Flutter、go
Projects
None yet
Development

No branches or pull requests

1 participant