How can I do this? I have tried to add the method printHappyBirthday() to onAppear() but onAppear() doesn’t get triggered after the SwiftUI view is updated:
struct ContentView: View {
@ObservedObject var randomViewModel: RandomViewModel
var body: some View {
Text("Hello World!")
.background(Color.random())
.onAppear {
printHappyBirthday()
}
}
}
When I posted my reply yesterday I was on my iPhone and I didn’t get to have a detailed look at your code you provided.
In this scenario you have provided, is the HelperView part of the View hierarchy in the project you are working with?
If it is, then how are you providing access to the ObservableObject? Are you passing it in from the parent View and then passing that to the HelperView?
In the code above, RandomViewModel is not being injected into the view Hierarchy. You’ve defined it as randomViewModel but that’s not enough to make it useable.
Also you are injecting a separate instance of the managedObjectContext into ContentView and HelperView.
The other point is that you have two views in WindowGroup. Why?
The accepted way to structure a project is that WindowGroup only calls one View which is the entry point to your App. If anything what you should do is this:
@main
struct siriswagApp: App {
let randomViewModel = RandomViewModel()
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
MainView()
.environment(randomViewModel)
.environment(persistenceController)
}
}
}
MainView (Note: I have not included any reference to your core data entity in subsequent Views).
struct HelperView: View {
@Environment(RandomViewModel.self) var randomViewModel
var body: some View {
Text("Hi")
.onTapGesture {
randomViewModel.randomNumber = randomViewModel.randomNumber + 1
print("Random number updated")
}
}
}
#Preview {
HelperView()
.environment(RandomViewModel())
}
RandomViewModel
// This conforms to the new iOS17 Observable Macro which means that
// randomNumber is effectively a Published property
@Observable
class RandomViewModel {
var randomNumber: Int
init(randomNumber: Int = 1) {
self.randomNumber = randomNumber
}
}