Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SwiftUI Multiple Selectable View Components
import SwiftUI
import Combine
final class MultipleSelectableViewModel: ObservableObject {
@Published var isSelectedRed: Bool = false
@Published var isSelectedGreen: Bool = false
@Published var isSelectedBlue: Bool = false
var cancels: [Cancellable] = []
init() {
let redSubscriber = $isSelectedRed.sink { (selected) in
print("red is\(selected ? "" : " not") selected")
}
cancels.append(redSubscriber)
let greenSubscriber = $isSelectedGreen.sink { (selected) in
print("green is\(selected ? "" : " not") selected")
}
cancels.append(greenSubscriber)
let blueSubscriber = $isSelectedBlue.sink { (selected) in
print("blue is\(selected ? "" : " not") selected")
}
cancels.append(blueSubscriber)
}
}
struct MultipleSelectableView: View {
@ObservedObject var viewModel = MultipleSelectableViewModel()
var body: some View {
ScrollView {
SelectBox(isSelected: $viewModel.isSelectedRed, color: .red)
SelectBox(isSelected: $viewModel.isSelectedGreen, color: .green)
SelectBox(isSelected: $viewModel.isSelectedBlue, color: .blue)
}
}
}
struct SelectBox: View {
@Binding var isSelected: Bool
let color: Color
var body: some View {
Rectangle()
.foregroundColor(color)
.frame(width: 100, height: 100)
.cornerRadius(10)
.onTapGesture {
self.isSelected.toggle()
}
.padding()
.border(Color.black, width: self.isSelected ? 4 : 0)
}
}
struct MultipleSelectableView_Previews: PreviewProvider {
static var previews: some View {
MultipleSelectableView()
}
}
@SatoTakeshiX

This comment has been minimized.

Copy link
Owner Author

@SatoTakeshiX SatoTakeshiX commented Jul 12, 2020

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.