gpt4 book ai didi

AppDelegate 和 ContentView() 之间的 SwiftUI 通信

转载 作者:行者123 更新时间:2023-12-04 10:00:46 26 4
gpt4 key购买 nike

我在 SwiftUI 应用程序上有一个静默的远程通知。它不是由 UNUserNotificationCenter 接收的,而是由旧的 AppDelegate didReceiveNotification 函数接收的。通知 ContentView() 发生更改的解决方案是什么? AppDelegate 中的 ObservableObject?

最佳答案

您可以声明符合 ObservableObject 的商店在 AppDelegate 中并将其设置为 ContentView 的环境对象。

// AppDelegate.swift
// in the class
let store = Store()

// in the applicationDidFinishLaunching(_:) method
window.contentView = NSHostingView(rootView: contentView.environmentObject(store))

// ContentView.swift
// in the struct
@EnvironmentObject var store: Store

环境对象是一个引用,因此您可以将值传递给它。与使用 ObservableObject 相同.完成更新后,只需调用 objectWillChange.send()或将该属性标记为@Published。并且 ContentView 将在通知后更新。

关于AppDelegate 和 ContentView() 之间的 SwiftUI 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61832113/

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