【问题标题】:SwiftUI How to make ForEach with Dict with array of custom objects auto updateSwiftUI 如何使用带有自定义对象数组的 Dict 进行 ForEach 自动更新
【发布时间】:2021-08-26 01:30:59
【问题描述】:

我有一个包含自定义类数组的字典,定义如下:

var coupons: [String: [Coupon]]

然后我将它们放入 ForEach 中,如下所示:

List {
                        
        ForEach(keys, id: \.self) { key in
                Section(header: Text(key)) {
                    ForEach(couponDict[key] ?? [], id: \.id) { coupon in
                            Button(ifexpiredString(date: coupon.date)+coupon.data[1]) {
                                     let coupons = UserDefaults.standard.coupons
                                     let couponIndex = coupons.firstIndex(of: coupon)
                                     self.currentview = "Coupon"+String(couponIndex!)
                            }.foregroundColor(ifexpired(date: coupon.date) ? Color.gray : ifexpireing(date: coupon.date))
                   }
           }
     }
}

我已经阅读了很多关于自动更新ForEachList 的答案,但没有一个使用字典,每个键下存储有一组自定义对象。更糟糕的是,我正在从UserDefaults 绘制couponDict。如何使 ListForEach 自动更新?

【问题讨论】:

  • 只是说,字典没有排序。因此,如果字典更改后出现问题,请不要感到惊讶。
  • 另外,为什么要删除swift 标签?它与问题相关,因为代码在 Swift 中。它还有助于 Stack Overflow 正确突出显示代码,因为它了解语言。
  • 啊,是的,我忘了提 - 我使用 map 按字母顺序对字典进行排序,这样就不会发生这种情况。我会添加 swift 标签。
  • 是的字典真的不是要走的路。而是尝试自定义 struct 的数组,其中包含 [Coupon]
  • @KunalKatiyar "使用map对字典进行排序" wdym?字典不可排序

标签: swift swiftui swiftui-list swiftui-foreach


【解决方案1】:

试试这样的:

List {
    ForEach(Array(coupons.keys), id: \.self) { key in 
    // or ForEach(coupons.keys.sorted(), id: \.self) { key in 
        Section(header: Text(key)) {
            ForEach(coupons[key] ?? [], id: \.id) { coupon in
                Button(ifexpiredString(date: coupon.date)+coupon.data[1]) {
                    let coupons = UserDefaults.standard.coupons
                    let couponIndex = coupons.firstIndex(of: coupon)
                    self.currentview = "Coupon"+String(couponIndex!)
                }.foregroundColor(ifexpired(date: coupon.date) ? Color.gray : ifexpireing(date: coupon.date))
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 2021-01-20
    相关资源
    最近更新 更多