10

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

1

1 Answer 1

4
  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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.