简体   繁体   中英

SwiftUI stops showing list updates after moving FetchRequest item to its own View struct

This was working:

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

So I moved part of this to its own View struct because the Xcode compiler started spazzing out:

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

Now I have this:

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

The problem is that since I moved it to its own View struct, the simulator no longer shows changes in the List like it did before when I made changes to the list or any of its relationships.

You have to pass your TodoList into TodoListLabel as a @Binding .

struct TodoListLabel: View {
    @Binding var todoList: TodoList

    var body: some View {
    // etc.
}

and then intialise it like this:

TodoListLabel(todoList: $todoList)

This way SwiftUI will know that TodoListLabel needs to be redrawn each time the TodoList item changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM