UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Navigating between views independently using EnvironmentObject

Forums > SwiftUI

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()) } }

3      

Hi Sally

You will need both the ObservableObject in scene delegate and preview

let viewRouter = ViewRouter()
let profile = Profile()

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    let sallyView = SallyView()
                         .environmentObject(viewRouter)
                         .environmentObject(profile)

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: sallyView)
        self.window = window
        window.makeKeyAndVisible()
    }
}

That probably why?

PS think the tutorial is old and not updated as they using passthough when @Pubilished is used now

3      

Thank you for your response. It actually worked!

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.