在SwiftUI中,当我在@State
中定义SceneDelegate
变量,然后将对应的绑定传递到所包含的ContentView时,即使@State
变量被更改,该视图也永远不会更新。
如果@State
变量是在ContentView
中定义的,并且我将绑定传递到子视图中,则在更改var时,该子视图的更新就很好。
为什么SceneDelegate
与@State
不兼容?是因为它没有使用相同的主体机制吗?关于@State
的事情是否仅在以后初始化,并且调用SceneDelegate的scene(scene:, willConnectTo:, options:)
时生成的任何绑定都是无效的?
请注意,这似乎与Update state of a screen struct from SceneDelegate无关,https://classic.yarnpkg.com/en/docs/cli/install/不会将var放在场景委托中。
以下是视图的示例代码,该视图在计时器触发时不会更新:
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()
}
}
}