How to show Menu programmatically in SwiftUI

I need to expand menu by some event in Swift UI. How can this be done?

struct ContentView: View {
    @State var openMenu = false
    var body: some View {
        Menu("Options") {
            Button("Order Now", action: placeOrder)
            Button("Adjust Order", action: adjustOrder)
            Button("Cancel", action: cancelOrder)
        }
    }

    func placeOrder() { }
    func adjustOrder() { }
    func cancelOrder() { }
}

For example, when openMenu variable changes, the menu expands

Upvotes: 12

Views: 4838

Answers (1)

rob mayoff
rob mayoff

Reputation: 385500

If you mean you want to make the menu appear on-screen, you cannot do that in pure SwiftUI as of 2021.

UIKit has showMenu(from:rect:), and AppKit has popUpContextMenu(_:with:for:), but SwiftUI has no API to show a menu programmatically.

In SwiftUI 2021, you can use confirmationDialog(_:isPresented:titleVisibility:presenting:actions:message:) or the deprecated ActionSheet type to present something menu-like.

Upvotes: 4

Related Questions