After following instructions from https://blckbirds.com/post/how-to-navigate-between-views-in-swiftui-by-using-an-environmentobject/#
My files have crashed. It won't let me preview it. When I run the simulator, it's giving me an error saying no observableobject of type Profile found. That should be in my class in the ContentView.
I have two environmentobjects and two observableobjects. One in the class in my contentview and one in the ViewRouter swift file. Could this be why it's crashing?
I already have the ContentView as my "page1"
I created two other view files. One is the SallyView file, which is going to be the parent view that will show "page1" first. And the other one is called SecondView.
I already have an environmentobject in my class in the ContentView that I use to access a variable from a textfield. But I had to create another observableobject in ViewRouter swift file which has the following code below. I wonder if this is the reason for the crash.
import Foundation
import Combine
import SwiftUI
class ViewRouter: ObservableObject {
let objectWillChange = PassthroughSubject<ViewRouter,Never>()
var currentPage: String = "page1" {
didSet {
withAnimation() {
objectWillChange.send(self)
}
}
}
}
The scene delegate looks like this one below.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: SallyView().environmentObject(ViewRouter()))
self.window = window
window.makeKeyAndVisible()
}
}
My ContentView is below.
class Profile: ObservableObject {
@Published var name = ""
convenience init (name: String) {
self.init()
self.name = name
}
}
struct ContentView: View {
@EnvironmentObject var viewRouter: ViewRouter
@EnvironmentObject var profile: Profile
var body: some View {
//my other codes are here as well
VStack {
Button(action: {self.viewRouter.currentPage = "page2"}) {
NextButtonContent()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(ViewRouter())
}
}
struct NextButtonContent : View {
var body: some View {
return Text("Next")
.foregroundColor(.white)
.frame(width: 200, height: 50)
.background(Color.blue)
.cornerRadius(15)
.padding(.top, 50)
}
}
My parentview is SallyView like below
import SwiftUI
struct SallyView: View {
@EnvironmentObject var viewRouter: ViewRouter
var body: some View {
VStack {
if viewRouter.currentPage == "page1" {
ContentView()
} else if viewRouter.currentPage == "page2" {
SecondView()
.transition(.scale)
}
}
}
}
struct SallyView_Previews: PreviewProvider {
static var previews: some View {
SallyView().environmentObject(ViewRouter())
}
}