swiftui - 在 SwiftUI 列表中重新加载单个行属性
问题描述
我试图让用户有机会保存或取消保存新闻文章。Save 按钮将其保存在后端,但后端更新时图像不会更新。
@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 接受。
推荐阅读
- angular - 如何在运行时设置 .scss 变量值?
- php - 无法在“php-jira-rest-client”中使用身份验证标头
- android - 将用户带到我的应用程序的评分页面会导致程序崩溃(仅在某些设备上)
- javascript - 无法使用 Nock 模拟外部 api
- java - Android Canvas DRAWTEXT POSITION CRAZY
- asp.net-mvc - AntiforgeryValidationException:提供的防伪令牌用于与当前用户不同的基于声明的用户
- html - CSS 问题:当我设置边距时,下面的 div 按钮被隐藏
- ldap - 就地修改 LDAP 对象类中的可能属性列表
- mysql - 如何在给予者价值之后获得下一个最小价值
- kotlin - 如何在 Kotlin 中为相关子类型实现 equals()