platojobs / SFLOG

Excerpted reading notes, is to read with their own study, work, research issues related to the sentences, paragraphs and so on according to the original text accurately transcription down. After extracting the original text, the source shall be indicated, including the title, author, publisher, date of publication, page number, etc., so as to facilitate quotation and verification. Excerpts should be selected, with usefulness as the standard for excerpts.
MIT License
5 stars 1 forks source link

Custom Toggle Switch #339

Open platojobs opened 2 months ago

platojobs commented 2 months ago
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()
}