Created
November 3, 2022 11:53
-
-
Save Joony/e3453a60e919629699ccd5bb536b8436 to your computer and use it in GitHub Desktop.
A SwiftUI implementation of a simple radio group for iOS
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
| private struct ColorToggle: View { | |
| @Binding var isOn: Bool | |
| let color: Color | |
| var body: some View { | |
| Toggle("", isOn: $isOn) | |
| .toggleStyle(ColorToggleStyle(color: color)) | |
| .buttonStyle(.borderless) | |
| } | |
| } | |
| private struct ColorToggleStyle: ToggleStyle { | |
| let color: Color | |
| func makeBody(configuration: Configuration) -> some View { | |
| Button(action: { | |
| configuration.isOn.toggle() | |
| }, label: { | |
| ZStack { | |
| Circle() | |
| .fill(color) | |
| .frame(width: 40, height: 40) | |
| if configuration.isOn { | |
| Circle() | |
| .stroke(color, lineWidth: 3) | |
| } | |
| } | |
| .frame(width: 48, height: 48) | |
| }) | |
| .contentShape(Circle()) | |
| } | |
| } | |
| struct ColorSwatchPickerView: View { | |
| let colors: [(Color, String)] | |
| private let columns = [ | |
| GridItem(.adaptive(minimum: 48)) | |
| ] | |
| @Binding var selectedColor: Color? | |
| var body: some View { | |
| LazyVGrid(columns: columns) { | |
| ForEach(colors, id: \.1) { color in | |
| ColorToggle(isOn: toggleBinding(color: color.0), color: color.0) | |
| .accessibilityLabel(color.1) | |
| } | |
| } | |
| } | |
| private func toggleBinding(color: Color) -> Binding<Bool> { | |
| Binding( | |
| get: { selectedColor == color }, | |
| set: { selected in selectedColor = selected ? color : nil } | |
| ) | |
| } | |
| } | |
| struct ColorSwatchPickerView_Previews: PreviewProvider { | |
| struct ColorSwatchPickerExampleView: View { | |
| private let colors: [(Color, String)] = [ | |
| (.red, "Red"), | |
| (.green, "Green"), | |
| (.orange, "Orange"), | |
| (.cyan, "Cyan"), | |
| (.indigo, "Indigo"), | |
| (.mint, "Mint"), | |
| (.pink, "Pink"), | |
| (.yellow, "Yellow"), | |
| (.teal, "Teal"), | |
| (.gray, "Gray") | |
| ] | |
| @State private var selectedColor: Color? = nil | |
| var body: some View { | |
| ColorSwatchPickerView(colors: colors, selectedColor: $selectedColor) | |
| } | |
| } | |
| static var previews: some View { | |
| Form { | |
| ColorSwatchPickerExampleView() | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The trick is in converting the
Binding<Color?>to aBinding<Bool>on line 54. Apart from that it's just a list ofToggleviews.