从SceneDelegate更新屏幕结构的状态 [英] Update state of a screen struct from SceneDelegate

查看:59
本文介绍了从SceneDelegate更新屏幕结构的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm coming from react-native and a beginner at Swift and SwiftUI and I was curious how to perform an action and update state on a specific screen when the app comes back into the foreground. I want to check the status of the notifications("allowed, "denied" etc.) and update the UI.

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

This is some example code - Here is the view I want to update:

struct Test: View {
    @State var isNotificationsEnabled : Bool

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

}

到目前为止,我一直在阅读的内容是您需要编辑 SceneDelegate.swift 内的 func sceneWillEnterForeground(_ scene:UIScene),但是到底该怎么做我从那里更新我的 Test 结构的状态吗?我在想我们需要某种全球状态,但这只是一个猜测.

So far what I've been reading is that you need to do edit the func sceneWillEnterForeground(_ scene: UIScene) inside SceneDelegate.swift but how on earth do I update the state of my Test struct from there? I'm thinking we need some kind of global state but that's just a guess.

有什么建议吗?

推荐答案

这是最简单的方法

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
        }
    }
}

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

Of course, if your application can have multiple scenes and you need to differentiate them somehow then more complicated variant of this approach will be needed to differentiate which scene generates this notification.

这篇关于从SceneDelegate更新屏幕结构的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆