Home > Software engineering >  swiftui: how to conditionally replace a CommandGroup?
swiftui: how to conditionally replace a CommandGroup?

Time:11-20

I'm using SwiftUI for my macOS app, and running into trouble trying to change the File menu depending on whether the user has purchased an upgrade.

I've got this:

.commands {
   CommandGroup(after: .newItem) {
       ExamplesMenu(name: "Open Example")
   }
   etc.
}

I want to disable the "New" command if the user hasn't purchased an upgrade, so that would be something like:

            if didPurchase {
                CommandGroup(after: .newItem) {
                    ExamplesMenu(name: "Open Example")
                }
            } else {
                CommandGroup(replacing: .newItem) {
                    ExamplesMenu(name: "Open Example")
                }
            }

However that yields the error:

Closure containing control flow statement cannot be used with result builder 'CommandsBuilder'

Is there a way of accomplishing this without ditching SwiftUI?

CodePudding user response:

you could try this:

.commands {
    didPurchase 
      ? CommandGroup(after: .newItem) { ExamplesMenu(name: "Open Example") }
      : CommandGroup(replacing: .newItem) { ExamplesMenu(name: "Open Example") }
}
  • Related