I have the following code:
final class State: ObservableObject {
@Published var isSelected = false
@Published var selectedColor: Color = .white
}
private enum Constants {
static let colors: [Color] = [.black, .white, .blue, .green, .yellow, .red]
}
var body: some View {
VStack(spacing: Constants.spacing) {
HStack {
Eraser()
ForEach(Constants.colors, id: \.self) { color in
PaintColor(color: color, isSelected: $state.isSelected)
.frame(maxWidth: .infinity)
}
}
.padding(Constants.colorsInsets)
}
.background(Constants.backgroundColor)
}
What I would actually like to do set isSelected
on PaintColor
to true
or false
based on the value of selectedColor
. Is it possible to map
a @Published
property? I want to do something like:
PaintColor(color: color, isSelected: state.selectedColor == color)
CodePudding user response:
It is possible with computable Binding, like
PaintColor(color: color, isSelected: Binding(
get: { state.selectedColor == color },
set: { state.selectedColor = $0 ? color : .white }
))
.frame(maxWidth: .infinity)
*actually if it is possible all unselected then it is needed to make selectedColor optional (and then reset to nil
instead of .white
above)
@Published var selectedColor: Color? = .white