我有一个类似于以下(简化)代码的应用程序架构。我使用WorkoutManager
StateObject
我在设置视图中初始化的 a,然后通过EnvironmentObject
. 问题是,在解除后,.sheet
没有任何生命周期事件可以初始化一个 new WorkoutManager
,我需要它才能连续开始新的锻炼。在下面的示例中,我如何WorkoutView
能够重新初始化 WorkoutManager 使其成为一个干净的对象?
import SwiftUI
import HealthKit
class WorkoutManager: ObservableObject {
var workout: HKWorkout?
}
struct ContentView: View {
@StateObject var workoutManager = WorkoutManager()
@State var showingWorkoutView = false
var body: some View {
Button {
showingWorkoutView.toggle()
} label: {
Text("Start Workout")
}
.sheet(isPresented: $showingWorkoutView) {
WorkoutView(showingWorkoutView: $showingWorkoutView)
}
}
}
struct WorkoutView: View {
@EnvironmentObject var workoutManager: WorkoutManager
@Binding var showingWorkoutView: Bool
var body: some View {
Text("Workout Started")
.padding()
Button {
showingWorkoutView.toggle()
//Here I want to initialize a new WorkoutManager to clear out the previous workout's state, how?
} label: {
Text("End Workout")
}
}
}