Skip to content

Instantly share code, notes, and snippets.

@hanrw
Created April 6, 2025 08:47
Show Gist options
  • Save hanrw/5cc605a8c9f431a4f4f1420651afed6a to your computer and use it in GitHub Desktop.
Save hanrw/5cc605a8c9f431a4f4f1420651afed6a to your computer and use it in GitHub Desktop.
SlidingToggleStyle
import SwiftUI
struct SlidingToggleStyle: ToggleStyle {
var activeColor: Color = .blue.opacity(0.5)
func makeBody(configuration: Configuration) -> some View {
HStack {
configuration.label
Spacer()
ZStack {
Rectangle()
.fill(configuration.isOn ? activeColor : Color(.systemGray5))
.clipShape(ContainerRelativeShape())
.frame(width: 36, height: 22)
.overlay {
Rectangle()
.fill(Color.white)
.frame(width: 15, height: 15)
.clipShape(ContainerRelativeShape())
.offset(x: configuration.isOn ? 6 : -6)
}
.onTapGesture {
withAnimation(.spring()) {
configuration.isOn.toggle()
}
}
}
.background(Color.clear, in: RoundedRectangle(cornerRadius: 6))
}
}
}
#Preview {
@Previewable @State var isOn = false
Group {
Toggle(isOn: $isOn) {
Text("Text")
}
.tint(.mint)
.toggleStyle(SlidingToggleStyle())
}
.padding()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment