问题描述
我试图让用户有机会保存或取消保存新闻文章。保存按钮将其保存在后端,但当后端更新时,图像不会更新。
@State var industryInsights = [IndustryInsight]()
List {
ForEach(industryInsights,id: \.self) { insight in
IndustryInsightRowView(insight: insight)
}
}
我不确定这样做的最佳方法,但我希望按钮图像在用户按下按钮时更新。任何帮助将不胜感激。
InsightClass 和属性
struct IndustryInsight: Codable,Hashable,Identifiable {
let id: Int
let industry,alert,date: String
let url: String
let status: String
}
按下保存按钮时的功能。
func saverowButtonClicked(alert: IndustryInsight) {
if alert.status == "Saved" {
RestAPI.changeStatusIndustryAlerts(id: alert.id,status: "Unsave",completionHandler: { () in
})
} else {
RestAPI.changeStatusIndustryAlerts(id: alert.id,status: "Save",completionHandler: { () in
})
}
}
解决方法
我尽量避免使用@State,而是使用@ObservableObject 和@Published。 尝试将您的 IndustryInsight 结构转换为 ObservableObject 类,并让 IndustryInsightRowView 作为 @ObservedObject 接受它。