簡體   English   中英

SwiftUI 在將 FetchRequest 項目移動到其自己的視圖結構后停止顯示列表更新

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

這是有效的:

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 結構中,模擬器不再像我之前對列表或其任何關系進行更改時那樣顯示列表中的更改。

您必須將 TodoList 作為 @Binding 傳遞給@Binding

struct TodoListLabel: View {
    @Binding var todoList: TodoList

    var body: some View {
    // etc.
}

然后像這樣初始化它:

TodoListLabel(todoList: $todoList)

這樣 SwiftUI 就會知道,每次 TodoList 項目更改時都需要重新繪制 TodoListLabel。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM