首页 > 解决方案 > SceneDelegate 中的@State 变量不更新绑定视图

问题描述

在 SwiftUI 中,当我@State在 a 中定义一个 var SceneDelegate,然后将相应的绑定传递给包含的 ContentView 时,即使@Statevar 已更改,该视图也不会更新。

如果@Statevar 是在其中定义的,ContentView并且我将绑定传递给子视图,则当 var 更改时,该子视图会更新得很好。

为什么不SceneDelegate使用@State?是因为它没有使用相同的身体机制吗?@State只是稍后才初始化并且调用 SceneDelegate 时生成的任何绑定scene(scene:, willConnectTo:, options:)都是无效的吗?

请注意,这似乎与来自 SceneDelegate 的屏幕结构的更新状态无关,后者不会将 var 放置在 Scene Delegate 中。

以下是计时器触发时不更新的视图的示例代码:

import SwiftUI

struct ContentView: View {
    @Binding var s : String
    var body: some View {
        Text(s)
    }
}

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    @State var show : String = "Initial value"
    var window: UIWindow?

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

        // Pass binding to our @State var to the enclosed content view
        let contentView = ContentView(s:$show)
    
        // Set a timer to change the @State var later
        Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { _ in
            // Explicitly run on the main queue, to rule
            // out the possibility of a queue problem
            DispatchQueue.main.async {
                self.show = "After timer"
            }
        }

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

标签: swiftui

解决方案


推荐阅读