Search code examples
iosswiftuicontextmenu

How to show context menu with preview?


I was wondering how to show a context menu when holding an element then showing a preview with the menu items in SwiftUI? I know how to show context menu items, but not with the preview and the animation.

View video: https://utilities.awesomeplayer.tech/send/f.php?h=35h_YJr5&p=1

I have tried to attach views inside the Context Menu, before the Buttons, but that has not worked.

Any help would be appreciated!


Solution

  • NOTE: The following is only available in iOS 16+ and iPadOS 16+. Earlier versions in second part. From the docs:

    This view modifier produces a context menu on macOS, but that platform doesn’t display the preview.

    Take a look at the docs here: https://developer.apple.com/documentation/swiftui/gridrow/contextmenu(menuitems:preview:). In iOS 16+, contextMenu accepts a preview argument that is some View. Example:

    struct myViewWithPreview: View{
    var body: some View{
      Text("Hold for contextMenu")
        .contextMenu{
          //ContextMenu stuff here
          //Such as buttons
            Button("Example"){}
       } preview: {//<-- HERE!!!!
          //Here, put any view that you want as a preview. For example, you could put a webview here on a link.
          //You could also do an image, such as how they do it on the docs.
           Text("Preview!")
       }
    }
    }
    

    If you are using earlier OS versions, you must do this using a custom approach. Take a look at this article. This could also be of use: https://onmyway133.com/posts/how-to-show-context-menu-with-custom-preview-in-swiftui/.