17

I have the following view:

struct ContentView: View {
    var body: some View {
        LinearGradient(gradient: Gradient(colors: [.blue, .red]), startPoint: .topTrailing, endPoint: .bottomLeading)
            .cornerRadius(16)
            .frame(width: 140, height: 140)
            .contextMenu {
                Button("", action: {})
            }
    }

}

However, when the ContextMenu is invoked, the edges are not rounded:

enter image description here

I've tried several things, such as:

  • Applying the clipShape modifier to clip it to a RoundedRectangle
  • Wrapping the gradient as the background of a RoundedRectangle view
  • Using a Color instead of a LinearGradient (which works as expected, but not what I need)

However none work. Any advice would be appreciated, thanks!

Richard Robinson
  • 867
  • 1
  • 11
  • 38

2 Answers2

27

Add the following code after .frame(...):

.contentShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
Daniel
  • 1,473
  • 3
  • 33
  • 63
Reed
  • 944
  • 7
  • 15
7

Updated for Swift 5.7.2

TLDR:

// Use the method that takes in ContentShapeKinds
.contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: 30))

Placed after .frame(...), and before .contextMenu { ... }


Detailed example:

var body: some View {
        VStack(alignment: .leading, spacing: .zero) {
            Text("Hello")
                .foregroundColor(.white)
                .font(.title)
        }
        .frame(maxWidth: .infinity, minHeight: 120)
        // These corner radii should match
        .background(RoundedRectangle(cornerRadius: 30).foregroundColor(.blue))
        .contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: 30))
        .contextMenu {
            Button("Look!") { print("We did it!") }
        }
    }

The above code produces a contextMenu that looks like this:

... instead of this:

ZGski
  • 2,398
  • 1
  • 21
  • 34