我正在使用 VIPER 架构使用 SwiftUI 编写我的项目,我遇到了调用 .onTapGesture 后我的图像没有更新的问题。以下是与此功能相关的代码块:
模型:
class FavoriteBeers{
var favoriteBeers = [Beer]()
}
交互者:
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)
}
主持人:
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)
}
}
看法:
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")
}
}
}
结果是
但是当我点击星号按钮时,它会打印“现在是最喜欢的/现在不是最喜欢的”,但图像不会改变。提前致谢!