我的macOS应用程序中有一个视图,当用户按下菜单栏中的undo和redo按钮时,需要通知该视图。在AppDelegate中,我让IBActions在用户按下undo/redo按钮时触发。IBAction通过通知中心发布通知,如下图所示:
extension Notification.Name {
static let undo = Notification.Name("undo")
static let redo = Notification.Name("redo")
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBAction func menuBarUndo(_ sender: Any) {
print("AppDelegate: pressed undo")
nc.post(name: .undo, object: nil)
}
@IBAction func menuBarRedo(_ sender: Any) {
print("AppDelegate: pressed redo")
nc.post(name: .redo, object: nil)
}
let nc = NotificationCenter.default
// applicationDidFinishLaunching and applicationWillTerminate not shown for brevity
}在我的ContentView中,有一个函数需要在用户按下undo/redo按钮时触发。它需要从ContentView内部触发,因为它依赖于该视图中包含的数据。如何在ContentView中订阅通知才能触发函数?
发布于 2020-04-26 11:48:07
在ContentView中,In可以如下所示
var body: some View {
VStack {
Text("Demo for receiving notifications")
.onReceive(NotificationCenter.default.publisher(for: .undo)) { _ in
/// call undo action
}
.onReceive(NotificationCenter.default.publisher(for: .redo)) { _ in
/// call redo action
}
}
}https://stackoverflow.com/questions/61432578
复制相似问题