Set a Preview Shape for Views Presenting Context Menus
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:
For reference, here’s what it would look like without any customization:
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 ✌️