首页 > 解决方案 > SwiftUI .contextMenu 使用 clipShape 在我的视图周围有可见的填充

问题描述

我在聊天气泡中有一张图片。这种效果是使用一个clipShape 来为气泡自定义形状来实现的。

当我附加一个 .contextMenu 并呈现 contextMenu 时,它会在聊天气泡周围显示一个填充。contextMenu 的默认cornerRadius 也剪裁了聊天气泡提示的一小部分。

我想要实现的是我可以在 Apple Messages 应用程序中看到的内容。在带有文本的消息上显示 contextMenu 会保留文本的 clipShape 而不添加填充。在图像上,它会删除 clipShape 并将图像调整为适当的纵横比。这两个我都无法实现。

struct ContentView: View {
    var body: some View {
        VStack {
            Image("leaf")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: 264, height: 361)
                .clipShape(Bubble(location: .rightBottom))
                .contentShape(Bubble(location: .rightBottom))
                .contextMenu(ContextMenu(menuItems: {
                    Button {
                    } label: {
                        HStack {
                            Text("Save")
                            Image(systemName: "arrow.down.to.line")
                        }
                    }
                }))
        }
        
    }
}

我曾尝试将 .contentShape 用于相同形状的气泡,但这根本没有效果。无论如何在下面的屏幕截图中显示没有圆角和左侧额外填充的 contextMenu?或者理想地使 contextMenu 容器背景清晰?

在此处输入图像描述

按下上下文菜单之前的图像:

在此处输入图像描述

标签: iosxcodeswiftuiswiftui-contextmenu

解决方案


解决方案非常简单。只需使用内容形状的第一个参数类型:

func contentShape<S>(_ kind: ContentShapeKinds, _ shape: S)

并将 kind 设置为 .contextMenuPreview:

Image("leaf")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 264, height: 361)
    .clipShape(Bubble(location: .rightBottom))
    .contentShape(.contextMenuPreview, Bubble(location: .rightBottom))
    .contextMenu(ContextMenu(menuItems: {
        Button {
        } label: {
            HStack {
                Text("Save")
                Image(systemName: "arrow.down.to.line")
            }
        }
    }))

推荐阅读