Reputation: 43
I would like to give the user the possibility to mark as preferred some films in a list of films. I wrote this code but when I click on the icon the symbol does not update.
What is the right way to do this?
the main class FIlmJSON is set as ObservableObject and allFilms is set as published
Film.swift
class Film: Codable, Identifiable, ObservableObject {
var id: UUID {
return UUID()
}
var filmname: String?
var developer: String?
var dilution: String?
var iso: String?
var mm35: String?
var mm120: String?
var temperature: String?
var brand: String?
var type: String?
var note: String?
}
// Avoid dealing with optional
extension Film {
var _filmname: String {
return filmname ?? ""
}
var _developer: String {
return developer ?? ""
}
var _dilution: String {
return dilution ?? ""
}
var _iso: String {
return iso ?? ""
}
var _mm35: String {
return mm35 ?? ""
}
var _mm120: String {
return mm120 ?? ""
}
var _temperature: String {
return temperature ?? ""
}
var _brand: String {
return brand ?? ""
}
var _type: String {
return type ?? ""
}
var _note: String {
return note ?? ""
}
}
FilmJSON.swift
class FilmJSON: Codable, ObservableObject, Identifiable {
var filmName: String
var films: [Film]
var isPreferred: Bool
init(filmName: String, films: [Film], isPreferred: Bool) {
self.filmName = filmName
self.films = films
self.isPreferred = isPreferred
}
Catalogue.swift
@Published var allFilms: [FilmJSON] = []
ContentView.swift
NavigationView {
VStack {
List {
ForEach(catalogue.allFilms) { film in
HStack {
Button {
film.isPreferred.toggle()
} label: {
Image(systemName: film.isPreferred ? "star.fill" : "star")
}
.buttonStyle(PlainButtonStyle())
NavigationLink(destination: DeveloperView(film: film)) {
Text("\(film.filmName)")
}
Spacer()
}
}
}
.listStyle(GroupedListStyle())
}
}
Upvotes: 0
Views: 380
Reputation: 1596
The Problem is that you are not updating the state of "film.isPreferred".
I guess that you are using a viewmodel and in this viewmodel you have to set the object or your array of the objects as a @Published variable.
For example :
@Published var foo : Foo
After this you will be able to change the value.
Upvotes: 1