SwiftUI macOS从子视图响应菜单栏操作



当用户按下菜单栏中的撤消和重做按钮时,我的macOS应用程序中有一个视图需要得到通知。在AppDelegate中,我有当用户按下undo/redo按钮时触发的IBActions。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中订阅通知以便触发该功能?

ContentView中可以如下

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

最新更新