Home > Mobile >  How can I remove macOS SwiftUI title options?
How can I remove macOS SwiftUI title options?

Time:06-05

So by default I am seeing this options for my app in macOS SwiftUI:

I would like to remove File, edit, view, window and just keeping help. How can I remove them?


I was trying to remove File, edit ... and I found this codes in internet, but not sure how I can make them works:

  @main
struct My_TestApp: App {
    
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    final class AppDelegate: NSObject, NSApplicationDelegate {
        
        func applicationWillUpdate(_ notification: Notification) {
            if let menu = NSApplication.shared.mainMenu {
                menu.items.removeFirst{ $0.title == "File" }
                menu.items.removeFirst{ $0.title == "Edit" }
                menu.items.removeFirst{ $0.title == "View" }
                menu.items.removeFirst{ $0.title == "Window" }
            }
        }
        
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

The Xcode error is:

Trailing closure passed to parameter of type 'Int' that does not accept a closure

CodePudding user response:

It is named Main Menu, just in case.

A possible approach is to filter created menu after launch. So create app delegate adapter and on did finish, do the following:

func applicationDidFinishLaunching(_ notification: Notification) {
    guard let mainMenu = NSApp.mainMenu else { return }
    let newMenu = NSMenu()
    if let appMenu = mainMenu.items.first {
        mainMenu.removeItem(appMenu) // cannot be in both, so remove from previous
        newMenu.addItem(appMenu)
    }
    if let helpMenu = NSApp.mainMenu?.items.last {
        mainMenu.removeItem(helpMenu)
        newMenu.addItem(helpMenu)
    }
    NSApp.mainMenu = newMenu   // << here !!
}

Tested with Xcode 13.4 / macOS 12.4

backup

  • Related