Pit Kal
Pit Kal

Reputation: 1

How to setup an EnvironmentObject in SwiftUI without SceneDelegate?

I want to set up an EnvironmentObject in SwiftUI with the new App Protocol @main --> NO Scene or AppDelegate. Am I allowed to setup EnvironmentsObjects in my Content View, not my @main .swift ? And if yes? Why can't I pass in the environment Object in my NavigationLink (as you can see) and Swift wants me to put the data in manually, I want to pass to the LoadingPage().

Thank you a lot !

import SwiftUI

struct ContentView: View {
    //MARK: Properties
    

    
    var body: some View {
        let user = UserData()
        //MARK: BODY
        TextPage().environmentObject(user)

On the TextPage() where I want to call the LoadingPage() within a NavLink

import SwiftUI
import Combine

struct TextPage: View {
    
    //MARK: Properties
    @EnvironmentObject var user : UserData
    
    @ObservedObject var post = Anfrage()
    
    @State var checkData = false // checkInput Var

    var body: some View {
        
        //MARK: Body
        NavigationView{
        
            VStack (alignment: .center, spacing: 30) {
            
   
            //NAV LINK
            NavigationLink(                                 
                destination: LoadingPage().environmentObject(user), isActive: $checkData) { EmptyView() }
                
```
And this is what Swift suggests me to correct:
LoadingPage(user: <#Environment<UserData>#>).environmentObject(user)

Upvotes: 0

Views: 687

Answers (1)

lorem ipsum
lorem ipsum

Reputation: 29299

Use a StateObject in your ContentView and then pass it as an EnvironmentObject

@StateObject var user : UserData = UserData()

BTW if you init variables in the body they will get re-initialized ever time the body gets reloaded by any of the properties with wrappers.

Upvotes: 1

Related Questions