Skip to content

Instantly share code, notes, and snippets.

@Joony
Created November 3, 2022 11:53
Show Gist options
  • Select an option

  • Save Joony/e3453a60e919629699ccd5bb536b8436 to your computer and use it in GitHub Desktop.

Select an option

Save Joony/e3453a60e919629699ccd5bb536b8436 to your computer and use it in GitHub Desktop.
A SwiftUI implementation of a simple radio group for iOS
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()
}
}
}
@Joony

Joony commented Nov 3, 2022

Copy link
Copy Markdown
Author

The trick is in converting the Binding<Color?> to a Binding<Bool> on line 54. Apart from that it's just a list of Toggle views.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment