简体   繁体   中英

SwiftUI - When I create multiplatform app, how to change view in scene?

I am trying to create a multi-platform app from SwiftUI.

Here is my code in in

@main
struct MyApp: App
@State var sceneManager = SceneManager.shared
    
    var body: some Scene {
        WindowGroup {
            
            if sceneManager.state == .landing {
                
                LandingPageView()
            } else if sceneManager.state == .historyRecord {
                
                HistoryRecordView()
            }
        }
    }

when my login did success, I will change SceneManager.shared property, from .landing to .historyRecord

but the view didn't change, how should I change root view of scene? Thanks

SwiftUI 2.0 introduced StateObject for such purpose, so go with the following pattern

@StateObject var sceneManager = SceneManager.shared

and make

class SceneManager: ObservableObject {
   @Published var state: StateTypeHere
}

Make your SceneManager an ObservableObject and change the @State wrapper to @ObservedObject .

Make sure state is an @Published variable.

https://developer.apple.com/documentation/combine/observableobject

Or you can change your @State to @State var sceneManagerState = SceneManager.shared.state

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM