使用切换 SwiftUI 更改自定义 class 的布尔值时遇到问题

Trouble changing boolean value of custom class using toggle SwiftUI

我有一个自定义的“家庭作业”class,它有一个“isComplete”布尔值。它显示在名为 HomeworkView 的自定义视图上。

HomeworkView 有一个名为 ToggleView 的子视图,它包含一个标签和切换开关,您猜对了,它显示作业是否完成。我不确定如何将其设置为 ToggleView 中的切换更改“作业”实例的值的位置。感谢对这个菜鸟的任何帮助。

我的class:-

class Homework {
    var title: String
    var details: String
    var isComplete: Bool
        
    init(title: String, details: String, isComplete: Bool) {
        self.title = title
        self.details = details
        self.isComplete = isComplete
    }
}

切换视图和作业视图:-

struct ToggleView: View {
    @State var isComplete: Bool
    
    var body: some View {
        HStack {
            Text("Is it complete?")
                .labelsHidden()
            
            VStack(alignment: .center) {
                Text(isComplete ? "YES" : "NO")
                    .foregroundColor(isComplete ? .green : .orange)
                
                Toggle("", isOn: $isComplete)
            }
            .padding(.horizontal)
            .frame(width: 80)
        }
        .padding()
    }
}

struct HomeworkView: View {
    @State var homework: Homework
    
    var body: some View {
        VStack {
            Text(homework.isComplete ? "COMPLETED" : "PENDING")
                .font(.largeTitle)
            
            ToggleView(isComplete: homework.isComplete)
                .onTapGesture {
                    print("\(homework.isComplete.hashValue)")
                }

        }
    }
}

@State 仅适用于 structs,因此首先,将 Homework 更改为 struct.

struct Homework {
    var title: String
    var details: String
    var isComplete: Bool
        
    /// no need for `init`, because structs get it for free!
}

然后,在HomeworkView中,你需要实例化homework@State变量通常需要在开始时实例化)。

@State var homework = Homework(title: "", details: "", isComplete: false)

最后,将 ToggleViewisComplete 更改为 @Binding

struct ToggleView: View {
    @Binding var isComplete: Bool

    ...
}

@Binding 使 Bool 值与 @State 同步。