9

I'm working on a new app using SwiftUI and I need some help in the context menu. I want to know how I can add a custom preview for the context menu in SwiftUI? & how I can group menu items in multiple groups & add children for any item in the menu? also how I can make the delete button in red color? or change the colors for them?

enter image description here enter image description here

another thing, how I can add a menu on the app icon to open a specific View or make an action like this: enter image description here

Adel Bassiony
  • 127
  • 2
  • 11
  • 1
    For the last question there is a tutorial form apple: https://developer.apple.com/documentation/uikit/menus_and_shortcuts/add_home_screen_quick_actions – KevinP Mar 23 '20 at 13:56

1 Answers1

2
  1. In order to add a custom preview, you can use this https://developer.apple.com/documentation/swiftui/view/contextmenu(menuitems:preview:) The preview should be something that conforms to View.

  2. To split the items in multiple groups, just add a Divider() between the items.

  3. In order to change the color to red for a Delete item, change the button role to .destructive as in the example below.

  4. To add children to one item, use a Menu as below, but I don't think this approach is encouraged.

Here is an example that includes all the above.

.contextMenu {
    Menu("This is a menu") {
        Button {
            doSomething()
        } label: {
            Text("Do something")
        }
    }
    
    Button {
        doSomethingAgain()
    } label: {
        Text("Something")
    }
    
    Divider()
    
    Button(role: .destructive) {
        performDelete()
    } label: {
        Label("Delete", systemImage: "trash")
    }
} preview: {
    Text("This is the preview") // you can add anything that conforms to View here
}