gpt4 book ai didi

ios - 从 SceneDelegate 更新屏幕结构的状态

转载 作者:行者123 更新时间:2023-12-01 19:35:52 24 4
gpt4 key购买 nike

我来自 react-native 和 Swift 和 SwiftUI 的初学者,我很好奇当应用程序回到前台时如何在特定屏幕上执行操作和更新状态。我想检查通知的状态(“允许”、“拒绝”等)并更新 UI。

这是一些示例代码 - 这是我要更新的 View :

struct Test: View {
@State var isNotificationsEnabled : Bool

var body : some View {
Toggle(isOn: self.isNotificationsEnabled) {
Text("Notifications")
}
}

}

到目前为止,我一直在阅读的是您需要编辑 func sceneWillEnterForeground(_ scene: UIScene)里面 SceneDelegate.swift但是我到底如何更新我的 Test 的状态?从那里构造?我认为我们需要某种全局状态,但这只是一个猜测。

有什么建议吗?

最佳答案

这是最简单的方法

struct Test: View {
@State private var isNotificationsEnabled : Bool

private let foregroundPublisher = NotificationCenter.default.publisher(for: UIScene.willEnterForegroundNotification)

var body : some View {
Toggle(isOn: self.$isNotificationsEnabled) {
Text("Notifications")
}
.onReceive(foregroundPublisher) { notification in
// do anything needed here
}
}
}

当然,如果您的应用程序可以有多个场景并且您需要以某种方式区分它们,那么将需要这种方法的更复杂的变体来区分哪个场景生成此通知。

关于ios - 从 SceneDelegate 更新屏幕结构的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60183545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com