swiftui - SceneDelegate 中的@State 变量不更新绑定视图
问题描述
在 SwiftUI 中,当我@State
在 a 中定义一个 var SceneDelegate
,然后将相应的绑定传递给包含的 ContentView 时,即使@State
var 已更改,该视图也不会更新。
如果@State
var 是在其中定义的,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()
}
}
}
解决方案
推荐阅读
- c++ - 默认模板类型给出错误,但显式类型没有
- apache - 我如何使用另一个 url 路径作为我的 cakephp 文件夹结构
- javascript - 如何修复 Jasmine 中的“$timeout 不是函数”错误?
- python - 计算字典熊猫列中的项目
- php - 如何在 PHP 中将 Windows-1251 字符串转换为 HEX
- azure - 如何使用凭据连接 til sql 数据库
- python - 如何使用 qPython 在 KDB 中插入一行
- mysql - 我无法返回值。ERROR 1415 (0A000): 不允许从函数返回结果集
- node.js - 如何调用 express 来触发外部重定向并避免 COR
- java - 有没有办法将公共 jar URL 作为 maven 依赖项包含在内?