[SC]()

iOS. Apple. Indies. Plus Things.

Set a Preview Shape for Views Presenting Context Menus

// Written by Jordan Morgan // Jul 13th, 2023 // Read it in about 1 minute // RE: Snips

This post is brought to you by Emerge Tools, the best way to build on mobile.

let concatenatedThoughts = """

Welcome to Snips! Here, you'll find a short, fully code complete sample with two parts. The first is the entire code sample which you can copy and paste right into Xcode. The second is a step by step explanation. Enjoy!

"""

The Scenario

When presenting a context menu from a SwiftUI view, it defaults to a rectangle shape. Here’s how you can change it:

import SwiftUI

struct RowContent: View {
    let image: String 

    var body: some View {
        Button {
            open()
        } label: {
            Image(systemName: image)
                .font(.largeTitle)
                .padding()
        }
        .buttonStyle(.plain)
        // 1
        .contentShape(ContentShapeKinds.contextMenuPreview, Circle())
        .contextMenu {
            Button {
                share()
            } label: {
                Label("Share", systemImage: "square.and.arrow.up")
            }
        }
    }
}

With that, the we get a nice, rounded preview shape when presenting the context menu:

Context menu presenting with a shape.

For reference, here’s what it would look like without any customization:

Context menu presenting with a default shape.

The Breakdown

Step 1
To customize the shape, simply use the .contentShape<S>(_ kind: ContentShapeKinds, _ shape: S) modifier and use contextMenuPreview for the first argument, along with the desired shape in the next one. That’s it - super easy, but easy to miss.

Until next time ✌️

···

Spot an issue, anything to add?

Reach Out.