When I select a cell, I want to deselect it from the other cell. After making the selection, I cannot remove the selection from the previous cell. What is the reason of this ? Sorry. I know little English.
Enum
enum Page {
case newest
case populer
case iPhone
case iPad
case mac
case watch
}
ViewModel
class MainViewModel: ObservableObject {
@Published var selectedTab = Page.newest
}
Category Model
struct Category: Identifiable {
var id = UUID()
var title: String
var icon: String
var color: Color
var page: Page
}
Basic Category
let basicCategory = [
Category(title: "En Yeniler", icon: "flame", color: .red, page: .newest),
Category(title: "Popüler", icon: "star", color: .yellow, page: .populer),
]
Cell
struct TabView: View {
var title: String = ""
var icon: String = ""
var color: Color
var page: Page
@ObservedObject var macMainVM = MainViewModel()
var body: some View {
Button(action: {
withAnimation(.spring(response: 0.5, dampingFraction: 0.6, blendDuration: 0)) {
self.macMainVM.selectedTab = self.page
}
}) {
VStack {
Image(systemName: icon)
.imageScale(.large)
.foregroundColor(color)
Text(title)
.font(.custom("Oswald-Light", size: 14))
.fixedSize()
}
.padding(5)
//I emphasize the choice here
.background(self.macMainVM.selectedTab == self.page ? RoundedRectangle(cornerRadius: 10).stroke(color) : nil)
}
.buttonStyle(PlainButtonStyle())
}
}
ForEach
VStack {
ForEach(basicCategory, id: .id) { item in
TabView(title: item.title, icon: item.icon, color: item.color, page: item.page)
}
}
3
Answers
Updated my answer with the working answer.
The problem was that you were using
@ObservedObject
instead of a@StateObject
Always use
@StateObject
for the parent view and@ObservedObject
for the children view.import SwiftUI
Below are the approaches for single selection and multiple selection.
For single selection you can pass
Page
as Bindings to subView.For multiple selection you can maintain a boolean state array, that can tell if current cell was already selected or not.
Single Selection
Multiple Selection
NOTE-: I haven’t explained what I did in deep, because it will be more understandable by looking into code.
The most Easy way: You should just use shared object, which you are creating new one every time! I did not edit your code! I just used a shared model! that was all I done! Or you can use environmentObject, and that would also solve the issue without shared one! both way is working!