What You Will Build
A custom toggle switch rotated 90 degrees with animated color transitions between red (off) and green (on). The thumb slides smoothly with a spring animation.
Why This Pattern Matters
Building a custom ToggleStyle lets you keep the standard binding while completely replacing the visual. The same technique works for custom checkboxes and radio buttons.
The Custom Toggle
struct RotatedToggle: View {
@State private var isOn = false
var body: some View {
VStack(spacing: 20) {
ZStack {
RoundedRectangle(cornerRadius: 15)
.fill(isOn ? Color.green : Color.red)
.frame(width: 60, height: 30)
.animation(.easeInOut(duration: 0.2), value: isOn)
Circle()
.fill(.white)
.frame(width: 28, height: 28)
.offset(x: isOn ? 15 : -15)
.animation(.spring(duration: 0.3), value: isOn)
}
.rotationEffect(.degrees(-90))
.onTapGesture { isOn.toggle() }
Text(isOn ? "ON" : "OFF")
.font(.headline)
.foregroundStyle(isOn ? .green : .red)
}
}
}
As a Reusable ToggleStyle
struct RotatedToggleStyle: ToggleStyle {
func makeBody(configuration: Configuration) -> some View {
ZStack {
RoundedRectangle(cornerRadius: 15)
.fill(configuration.isOn ? Color.green : Color.red)
.frame(width: 60, height: 30)
Circle()
.fill(.white)
.frame(width: 28, height: 28)
.offset(x: configuration.isOn ? 15 : -15)
}
.rotationEffect(.degrees(-90))
.animation(.spring(duration: 0.3), value: configuration.isOn)
.onTapGesture { configuration.isOn.toggle() }
}
}
// Usage:
Toggle("Dark Mode", isOn: $isDarkMode)
.toggleStyle(RotatedToggleStyle())
Tips
- Use ToggleStyle in production for proper accessibility and binding support.
- Add haptic feedback on toggle for a polished feel.
iOS Version: iOS 15+