I'm writing my project with SwiftUI using VIPER architecture and I faced with the problem that my image is not updating after calling .onTapGesture. Here is the code blocks that relates to this functionality:
Model:
class FavoriteBeers{
var favoriteBeers = [Beer]()
}
Interactor:
func addToFavorites(beer: Beer){
favoriteBeers.favoriteBeers.append(beer)
saveFavoriteBeers()
}
func removeFromFavorites(_ beer: Beer) {
favoriteBeers.favoriteBeers.removeAll { $0 == beer }
saveFavoriteBeers()
}
func isFavorite(_ beer: Beer) -> Bool {
favoriteBeers.favoriteBeers.contains(beer)
}
Presenter:
func favoritesButton(_ beer: Beer) -> String{
if isFavorite(beer){
return SystemImages.FilledStar.rawValue
}else{
return SystemImages.EmptyStar.rawValue
}
}
private func isFavorite(_ beer: Beer) -> Bool{
return interactor.isFavorite(beer)
}
func addOrRemoveFromFavorites(_ beer: Beer){
if isFavorite(beer){
print("now not favourite")
interactor.removeFromFavorites(beer)
}else{
print("now favourite")
interactor.addToFavorites(beer: beer)
}
}
View:
struct BeersListView: View{
@StateObject var presenter : BeersListPresenter
var body: some View {
NavigationView{
List{
ForEach(presenter.beers, id: \.id){ beer in
HStack{
VStack(alignment: .leading){
Text(beer.name)
.font(.headline)
Text("Vol: \(presenter.formattedABV(beer.abv))")
.font(.subheadline)
}
Spacer()
Image(systemName: presenter.favoritesButton(beer))
.frame(width: 13, height: 13)
.foregroundColor(.yellow)
.onTapGesture {
withAnimation{
presenter.addOrRemoveFromFavorites(beer)
}
}
}
}
}.onAppear{
presenter.loadList(at: 1)
} .listStyle(GroupedListStyle())
.navigationBarTitle("All beers")
}
}
}
And result is
But when I tap on star button it prints "now is favourite/now is not favourite" but image does not change. Thanks in advance!
Solved. Just added objectWillChange in addOrRemoveFromFavorites method