首页 > 解决方案 > 将 FetchRequest 项目移动到自己的 View 结构后,SwiftUI 停止显示列表更新

问题描述

这是有效的:

ForEach(todoLists, id: \.self) {todoList in
    NavigationLink(destination: TodoItemView(todoList: todoList), label: {
        HStack {
            if (todoList.countChecked == todoList.countTotal) {
                Text(todoList.title!)
                    .foregroundColor(stringToColor(string: todoList.color!))
                    .strikethrough()
            }
            else {
                Text(todoList.title!)
                    .foregroundColor(stringToColor(string: todoList.color!))
            }
            Spacer()
            Text(String(todoList.countChecked) + " / " + String(todoList.countTotal))
                .foregroundColor(.gray)
                .font(.footnote)
        }
    })
}

所以我将其中的一部分移到了它自己的 View 结构中,因为 Xcode 编译器开始出现问题:

struct TodoListLabel: View {
    var todoList: TodoList

    var body: some View {
        HStack {
            if (todoList.countChecked == todoList.countTotal) {
                Text(todoList.title!)
                    .foregroundColor(stringToColor(string: todoList.color!))
                    .strikethrough()
            }
            else {
                Text(todoList.title!)
                    .foregroundColor(stringToColor(string: todoList.color!))
            }
            Spacer()
            Text(String(todoList.countChecked) + " / " + String(todoList.countTotal))
                .foregroundColor(.gray)
                .font(.footnote)
        }
    }
}

现在我有这个:

ForEach(todoLists, id: \.self) {todoList in
    NavigationLink(destination: TodoItemView(todoList: todoList), label: {
        TodoListLabel(todoList: todoList)
    })
}

问题是,由于我将它移到了它自己的 View 结构中,模拟器不再像我之前对列表或其任何关系进行更改时那样显示列表中的更改。

标签: iosswiftswiftui

解决方案


您必须将 TodoList 作为@Binding.

struct TodoListLabel: View {
    @Binding var todoList: TodoList

    var body: some View {
    // etc.
}

然后像这样初始化它:

TodoListLabel(todoList: $todoList)

这样 SwiftUI 将知道 TodoListLabel 每次 TodoList 项目更改时都需要重新绘制。


推荐阅读