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

彼得·肖恩

我的 macOS 应用程序中有一个视图,当用户按下菜单栏中的撤消和重做按钮时,需要通知该视图。在 中AppDelegate,我有 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我有一个需要在用户按下撤消/重做按钮时触发的功能。它需要从内部触发,ContentView因为它依赖于该视图中包含的数据。如何从内部订阅通知ContentView以便触发该功能?

他的脾气

ContentViewin 可以如下

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章