Adel Bassiony
Adel Bassiony

Reputation: 187

Context Menu & Haptic touch in SwiftUI

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

Upvotes: 10

Views: 2629

Answers (1)

Robert Basamac
Robert Basamac

Reputation: 406

  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
}

Upvotes: 4

Related Questions