简体   繁体   English

SwiftUI - 当我创建多平台应用程序时,如何更改场景中的视图?

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

I am trying to create a multi-platform app from SwiftUI.我正在尝试从 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当我登录成功时,我将更改 SceneManager.shared 属性,从.landing.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 SwiftUI 2.0为此目的引入了StateObject ,因此请使用以下模式

@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 .使您的SceneManager成为ObservableObject并将@State包装器更改为@ObservedObject

Make sure state is an @Published variable.确保state是一个@Published变量。

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

Or you can change your @State to @State var sceneManagerState = SceneManager.shared.state或者您可以将@State更改为@State var sceneManagerState = SceneManager.shared.state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何更改 SwiftUI 应用程序(无 SceneDelegate 或 AppDelegate)中的根视图? - How can I change the root view in a SwiftUI app (no SceneDelegate or AppDelegate)? 在 SwiftUI 中点击 watchOS 应用程序时如何更改图像 - How do I change image when tapped on it watchOS app in SwiftUI SwiftUI:多平台应用程序 swiftui 意外的平台条件 - SwiftUI: Multiplatform app swiftui unexpected platform condition 如何使用 SwiftUI 更改根视图 - How do I change the root view with SwiftUI 如何在 SwiftUI 中创建此视图? - How can I create this view in SwiftUI? SwiftUI:如何在后台应用程序时添加带有应用程序徽标的模糊视图? - SwiftUI: How to add Blur view with app logo when app in background? 在 macOS 上运行多平台 SwiftUI 应用程序时,是否可以跳过 launchscreen.storyboard 文件? - Is it possible to skip launchscreen.storyboard file when running a multiplatform SwiftUI app on macOS? 我如何使用 ipad Playground for swift 在 swiftUI 上运行 Scene 和 App - How can i run Scene and App on swiftUI using ipad Playground for swift 如何创建仅在使用 SwiftUI 打开应用程序时出现的警报? - How do I create an alert which only appears when app is opened with SwiftUI? 如何在swiftUI中创建普通视图 - How to create a plain view in swiftUI
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM