Main menu in SwiftUI App

Maybe I missed something — is it possible to somehow edit / change / customise main menu in SwiftUI App lifecycle? I made a document based App, I can read, write, even Recent Documents have for free. But how to add or remove Items, and connect them with app in pure SwiftUI way? With no AppKit, pure?

Replies

Use the .commands modifier, such as:
Code Block
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}.commands {
CommandGroup(replacing: .help) {
Button(action: {....}) {
Text("MyApp Help")
}
}
CommandMenu("Edit") {
...
}
}
}
}
Thanks, it look promising. But if I use this code (filled dots with {print ("hello")} and Text("..."), app hangs up and prints in console:


Code Block
2020-11-20 11:44:39.064295+0100 GlyphDesigner[45633:2671193] [Layout] Unable to simultaneously satisfy constraints:
    "<NSAutoresizingMaskLayoutConstraint:0x60000119abc0 h=-&- v=-&- _NSTextContentView:0x7fee4561c870.minX == 0   (active, names: '|':NSTextView:0x7fee45673c80 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x60000119ada0 h=-&- v=-&- H:[_NSTextContentView:0x7fee4561c870]-(380)-|   (active, names: '|':NSTextView:0x7fee45673c80 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x60000119ae90 h=--& v=--& NSTextView:0x7fee45673c80.width == 318   (active)>"
)
Will attempt to recover by breaking constraint 
<NSAutoresizingMaskLayoutConstraint:0x60000119ada0 h=-&- v=-&- H:[_NSTextContentView:0x7fee4561c870]-(380)-|   (active, names: '|':NSTextView:0x7fee45673c80 )>
Set the NSUserDefault NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints to YES to have -[NSWindow visualizeConstraints:] automatically called when this happens.  And/or, set a symbolic breakpoint on LAYOUT_CONSTRAINTS_NOT_SATISFIABLE to catch this in the debugger.


But I have no idea where to set constrains in this case.
I cannot replicate your error, all is working fine for me on:
macos 11, using xcode 12. What system are you using?
Code Block
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}.commands {
CommandGroup(replacing: .help) {
Button(action: {print("clicked on MyApp Help menu")}) {
Text("MyApp Help")
}
}
CommandMenu("Edit") {
Text("edit menu item")
}
}
}
}
struct ContentView: View {
var body: some View {
Text("test").padding()
}
}