Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SingleSelectableView.swift
enum BoxType: String {
case unknown
case red
case green
case blue
}
final class SingleSelectableBoxViewModel: ObservableObject {
@Published var selectedBox: BoxType = .unknown
var cancels: [AnyCancellable] = []
init() {
let selected = $selectedBox.sink { (box) in
print("selected box is \(box.rawValue)")
}
cancels.append(selected)
}
}
struct ParentView: View {
@ObservedObject var viewModel = SingleSelectableBoxViewModel()
var body: some View {
VStack {
SingleSelectableBoxView(selectedBox: $viewModel.selectedBox)
Text("Selected box is \(viewModel.selectedBox.rawValue)")
}
}
}
struct ParentView_Previews: PreviewProvider {
static var previews: some View {
ParentView()
}
}
struct SingleSelectableBoxView: View {
@Binding var selectedBox: BoxType
var body: some View {
ScrollView {
BoxView(selectedBox: $selectedBox, color: .red, boxType: .red)
BoxView(selectedBox: $selectedBox, color: .green, boxType: .green)
BoxView(selectedBox: $selectedBox, color: .blue, boxType: .blue)
}
}
}
struct SingleSelectableBoxView_Previews: PreviewProvider {
static var previews: some View {
SingleSelectableBoxView(selectedBox: .constant(.red))
}
}
struct BoxView: View {
@Binding var selectedBox: BoxType
let color: Color
let boxType: BoxType
var body: some View {
Rectangle()
.foregroundColor(color)
.frame(width: 100, height: 100)
.cornerRadius(10)
.onTapGesture {
self.selectedBox = self.boxType
}
.padding()
.border(Color.black, width: selectedBox == boxType ? 4 : 0)
}
}
@SatoTakeshiX

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.