【问题标题】:SwfitUI @FetchedResults one-many relationship didn't update properlySwiftUI @FetchedResults 一对多关系没有正确更新
【发布时间】:2020-11-10 08:14:02
【问题描述】:

我正在使用带有 Coredata 的 SwiftUI 来显示一对多的关系数据元素。

例子:

一个Group 有多个Book

我有两个视图,GroupView 有很多 GroupRowViews。

struct GroupView: View {

    var groups: FetchedResults<Group>

    var body: some View {
        ScrollView(.horizontal) {
            HStack(alignment: .center, spacing: 32, content: {

                ForEach(contractGroups) { group in
                    HStack {
                        GroupRowView(group: group)
                        Text(String(group.books?.count ?? 0)) // display correct
                                            .foregroundColor(Color.red)
                    }

                }

            })
        }
    }
}

GroupRowView 在这里:

struct GroupRowView: View {

    var group: Group

    var body: some View {
        ZStack {

            Color(.white)
            VStack {
                Text(group.name!)
                    .foregroundColor(Color.white)
                    .font(.system(size: 17, weight: .bold, design: .default))

                Text(String(group.books?.count ?? 0)) //display wrong
                    .foregroundColor(Color.white)
            }
        }.frame(width: 120, height: 100, alignment: .center)
    }
}

每次更新books 时,图书计数都会在GroupView 中正确显示,但不会在GroupRowView 中显示。

forEach中的groupFetchedResults&lt;ContractGroup&gt;.Element,是不是和GroupRowView中的var group: ContractGroup不一样的原因?

如何使GroupRowView 中的group.books 得到更改?

谢谢!

【问题讨论】:

    标签: ios swift core-data swiftui


    【解决方案1】:

    你需要在行中明确观察group,比如

    struct GroupRowView: View {
    
        @ObservedObject var group: Group
    
        // ... other code
    

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多