3

Set a Preview Shape for Views Presenting Context Menus

 1 year ago
source link: https://www.swiftjectivec.com/snip-context-menu-preview-shape-in-swiftui/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Set a Preview Shape for Views Presenting Context Menus

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

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 ✌️


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK