I have problem when i click the favourite button it does not update the view of single book information so the book will be favourite. but when i go back to the list of book and i reselect the book it is favourite. what did i do wrong?
Welcome to the community!!
Have you checked your code to the provided solution?
Hi Manolis,
This catches everyone out and it’s to do with the difference between a class and a struct
Is your data model a class or a struct? If it is a class then change it to a struct.
Hello i checked the code and i cannot find what i am doing wrong i even did a second small code to change if it working the change
class thedata : Identifiable, Decodable{
var theid:UUID
var likes:Bool
var name:String
var id:Int
init(){
theid=UUID()
likes=false
name="defaultname"
id=0
}
}
then i retrieve the data
class mydata : ObservableObject{
@Published var allll = [thedata]()
init(){
var onedata:thedata = thedata()
onedata.theid=UUID()
onedata.likes=false
onedata.name="name1"
onedata.id=1
allll.append(onedata)
onedata = thedata()
onedata.theid=UUID()
onedata.likes=false
onedata.name="name2"
onedata.id=2
allll.append(onedata)
onedata = thedata()
onedata.theid=UUID()
onedata.likes=false
onedata.name="name3"
onedata.id=3
allll.append(onedata)
onedata = thedata()
onedata.theid=UUID()
onedata.likes=false
onedata.name="name4"
onedata.id=4
allll.append(onedata)
}
func changeLike(theselectedid:UUID){
if let k = allll.firstIndex(where: {$0.theid == theselectedid}){
print("found it: "+String(allll[k].likes))
allll[k].likes.toggle()
print("changed it")
}
}
}```
the list view
struct ContentView: View {
@ObservedObject var thedate=mydata()
var body: some View {
nextView().environmentObject(thedate)
}
}
struct nextView: View {
@EnvironmentObject var dataModel:mydata
var body: some View {
Text("Hello, World!\(dataModel.allll.count)")
NavigationView{
ScrollView{
LazyVStack{
ForEach (0..<dataModel.allll.count){ r in
NavigationLink(
destination: changing(selectedData: dataModel.allll[r]),
label: {
Text("\(dataModel.allll[r].name) ")
})
}
}
}
}
}
}
and the place where i change the data
struct changing: View {
var selectedData:thedata
@EnvironmentObject var dataModel:mydata
var body: some View {
Button {
dataModel.changeLike(theselectedid: selectedData.theid)
} label: {
VStack{
Text(“The name (selectedData.name)”)
Image(systemName: selectedData.likes ? “star.fill” : “star”)
.resizable()
.frame(width: 28, height: 28)
}
}
}
}
the likes changes but in the view where i change the data it does not show the change. I must go back to the list and when i rerender the data it shows the changed data.
What am i doing wrong?
Thanks
I found the problem the problem was that i should set thedata as struct and not as class but why there was problem when the thedata was class?