【问题标题】:Update state of a screen struct from SceneDelegate从 SceneDelegate 更新屏幕结构的状态
【发布时间】:2020-02-12 07:55:24
【问题描述】:

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

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

struct Test: View {
    @State var isNotificationsEnabled : Bool

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

}

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

有什么建议吗?

【问题讨论】:

    标签: ios swift iphone swiftui


    【解决方案1】:

    这是最简单的方法

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      相关资源
      最近更新 更多