隐藏 SwiftUI / MacOS 应用程序的编辑菜单

Hiding Edit Menu of a SwiftUI / MacOS app

我的 MacOS 应用程序没有任何文本编辑功能。如何隐藏自动添加到我的应用程序的 Edit 菜单?我更愿意在 SwiftUI 中执行此操作。

我希望下面的代码应该可以工作,但它没有。

@main
struct MyApp: App {

var body: some Scene {
    WindowGroup {
        ContentView()
    }.commands {
        CommandGroup(replacing: .textEditing) {}
    }
}

}

据我所知,您无法隐藏整个菜单,您可以只隐藏其中的元素组:

    .commands {
        CommandGroup(replacing: .pasteboard) { }
        CommandGroup(replacing: .undoRedo) { }
    }

对于原生(Cocoa)应用程序

可以使用 NSApplicationDelegate 删除应用程序菜单。此方法可能会在未来的 macOS 版本中中断(例如,如果 Edit 菜单的位置发生变化),但目前有效:

class MyAppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
  let indexOfEditMenu = 2
   
  func applicationDidFinishLaunching(_ : Notification) {
    NSApplication.shared.mainMenu?.removeItem(at: indexOfEditMenu)
  }
}


@main
struct MyApp: App {
  @NSApplicationDelegateAdaptor private var appDelegate: MyAppDelegate

  var body: some Scene {
    WindowGroup {
      ContentView()
    }.commands {
      // ...
    }
  }
}

对于 Catalyst (UIKit) 应用

对于 Catalyst-based macOS 应用程序,方法与上述类似,只是使用了从 UIResponder 派生的 UIApplicationDelegate

class MyAppDelegate: UIResponder, UIApplicationDelegate, ObservableObject {
   override func buildMenu(with builder: UIMenuBuilder) {
      /// Only operate on the main menu bar.
      if builder.system == .main {
         builder.remove(menu: .edit)
      }
   }
}


@main
struct MyApp: App {
  @UIApplicationDelegateAdaptor private var appDelegate: MyAppDelegate

  var body: some Scene {
    WindowGroup {
      ContentView()
    }.commands {
      // ...
    }
  }
}