首页 > 解决方案 > 在 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
        })
    }
}

标签: swiftuiswiftui-list

解决方案


我试图尽可能避免使用@State,而是使用@ObservableObject 和@Published。尝试将您的 IndustryInsight 结构转换为 ObservableObject 类,并让 IndustryInsightRowView 将其作为@ObservedObject 接受。


推荐阅读