实例状态未更新——SwiftUI

State of an instance is not updating -- SwiftUI

所以我有这个结构任务,它有一个@State 完成:

struct Task:Identifiable{
    var id: Int
    @State var completion:Bool = false
    var priority:String? = nil
    @State var completionDate:Date? = nil
    var creationDate:Date
    var fullDescription:String
}

在 TaskItem:View 中,我正在尝试创建一个复选框来正确更新状态:

struct TaskItem: View {
    
    @State var task:Task
    @State var isChecked:Bool = false
    
    func toggle(){
        isChecked = !isChecked
        task.completion = isChecked
        if isChecked {
            task.completionDate = Date()
        } else {
            task.completionDate = nil
        }
    }
    
    var body: some View {
       
                    Button(action: toggle){
                        
                       Image(systemName: isChecked ? "square.split.diagonal.2x2": "square")
                        
      
            
            
        }
        
    }
}

但是即使 isChecked 发生了变化,图像也发生了变化,task.completion 却没有。我该如何解决这个问题?

我目前正在使用它来查看它:

struct TaskItem_Previews: PreviewProvider {
    static var previews: some View {
        let task =  testTask()
        TaskItem(task: task)
    }
}

@State 属性 包装器不适合在数据模型中使用,例如您的结构任务。 @State 属性 包装器是一个 属性 包装器,旨在用于 SwiftUI 视图。如果你删除@State,你应该处于良好状态。

不要像在 Task 中那样在 View 之外使用 @State。它们只能在 View.

中使用

解释@Statedocs很有用:

"... You should only access a state property from inside the view’s body, or from methods called by it. For this reason, declare your state properties as private, to prevent clients of your view from accessing them. It is safe to mutate state properties from any thread....".

注意:Swift 也有一个 Task 结构,这是一个异步工作单元。这可能会成为一个问题 如果您对 Task 结构使用相同的名称。