在SwiftUI中,带有圆角的线性渐变上下文菜单会产生锐利的边缘。

17

我有以下看法:

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: {})
            }
    }

}

然而,当ContextMenu被调用时,边缘并没有被圆角化:

在此输入图片描述

我尝试了几种方法,例如:

  • clipShape修饰符应用于将其剪辑为RoundedRectangle
  • 将渐变作为RoundedRectangle视图的背景包装
  • 使用颜色而不是线性渐变(它按预期工作,但不是我需要的)

然而,这些都不起作用。任何建议都将不胜感激,谢谢!

2个回答

28

.frame(...) 后面添加以下代码:

.contentShape(RoundedRectangle(cornerRadius: 16, style: .continuous))

9

更新至Swift 5.7.2

简而言之:

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

放置在.frame(...)之后,.contextMenu { ... }之前


详细示例:

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!") }
        }
    }

上面的代码生成了一个类似于这样的contextMenu: ...而不是这样的:

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接