【问题标题】:Reloading individual rows properties in SwiftUI List在 SwiftUI 列表中重新加载单个行属性
【发布时间】:2021-07-06 16:39:43
【问题描述】:

我试图让用户有机会保存或取消保存新闻文章。保存按钮将其保存在后端,但后端更新时图像不会更新。

@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
        })
    }
}

【问题讨论】:

  • 在 SwiftUI 中,您不能真正重新加载单个行,只需让系统处理即可。在changeStatusIndustryAlerts闭包中,修改industryInsights数组,List会自动更新。
  • @aheze 谢谢你,你能告诉我你的意思吗.. 虽然行业洞察数组在另一个类中
  • 您需要更新您的 industryInsights @State 变量。
  • @LukeTomlinson 你的saverowButtonClicked func 在哪个类?它必须以某种方式与您的 ContentView 相关
  • @aheze 当按下按钮时,我有一个 RowView(),其中包含所有这些功能。然后在我的 contentView() 我有一个 RowView() 列表

标签: swiftui swiftui-list


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    相关资源
    最近更新 更多