|
import SwiftUI |
|
|
|
// MARK: RadioButtons |
|
|
|
struct RadioButtons: View { |
|
var questions: [String] = ["Yes", "No"] |
|
@Binding var selected: Int? |
|
|
|
var onSymbol = "largecircle.fill.circle" |
|
var offSymbol = "circle" |
|
|
|
var separator = " " |
|
|
|
var body: some View { |
|
Group { |
|
ForEach(questions.indices) { index in |
|
let tokens = questions[index].components(separatedBy: separator) |
|
let answer = tokens[0] |
|
let question = tokens.dropFirst().joined(separator: separator) |
|
|
|
Button(action: { |
|
selected = selected == index && questions.count == 1 ? nil : index |
|
}, label: { |
|
HStack(alignment: .firstTextBaseline) { |
|
Image(systemName: selected == index ? onSymbol : offSymbol) |
|
.foregroundColor(.accentColor) |
|
Group { |
|
Text(answer) |
|
.bold() |
|
+ Text(" \(question)") |
|
.foregroundColor(Color(.label)) |
|
}.padding(.vertical, 2) |
|
} |
|
}) |
|
} |
|
} |
|
} |
|
|
|
} |
|
|
|
// MARK: - Examples |
|
|
|
struct RadioButtons_Examples: View { |
|
|
|
@State var two: Int? |
|
@State var one: Int? |
|
@State var none: Int? |
|
@State var many: Int? |
|
|
|
var body: some View { |
|
Form { |
|
Section(header: Text("Custom")) { |
|
RadioButtons(questions: [ |
|
"Cheese I like cheese, and I think this multi-line text looks okay with the vertical alignment set to firstTextBaseline", |
|
"No I prefer vegan cheese"], |
|
selected: $two) |
|
} |
|
Section(header: Text("SINGLE")) { |
|
RadioButtons(questions: ["You can even unselect single items, though I'll probably want a different control altogether for multi-checkbox behaviors"], selected: $one) |
|
} |
|
Section(header: Text("DEFAULTS")) { |
|
RadioButtons(selected: $none) |
|
} |
|
Section(header: Text("MANY")) { |
|
RadioButtons(questions: [ |
|
"1 One", |
|
"2 Two", |
|
"3 Three", |
|
"4 Four", |
|
], selected: $many) |
|
} |
|
Section(header: Text("DISABLED")) { |
|
RadioButtons(selected: $none).disabled(true) |
|
} |
|
Section(header: Text("EMPTY ARRAY")) { |
|
RadioButtons(questions: [], selected: $none) |
|
} |
|
Section(header: Text("EMPTY STRING")) { |
|
RadioButtons(questions: [" "], selected: $none) |
|
} |
|
}.navigationTitle("Radio Buttons") |
|
} |
|
} |
|
|
|
// MARK: - Preview |
|
|
|
struct RadioButtons_Previews: PreviewProvider { |
|
|
|
static var previews: some View { |
|
RadioButtons_Examples() |
|
} |
|
} |