Reputation: 187
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?
another thing, how I can add a menu on the app icon to open a specific View or make an action like this:
Upvotes: 10
Views: 2629
Reputation: 406
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
.
To split the items in multiple groups, just add a Divider()
between the items.
In order to change the color to red for a Delete
item, change the button role to .destructive
as in the example below.
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