Created
April 6, 2025 08:47
-
-
Save hanrw/5cc605a8c9f431a4f4f1420651afed6a to your computer and use it in GitHub Desktop.
SlidingToggleStyle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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