Set a Preview Shape for Views Presenting Context Menus
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.
Set a Preview Shape for Views Presenting Context Menus
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 ✌️
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK