首页 > 解决方案 > SwiftUI 如何将 contextMenu 添加到列表行中的图像并保持圆角并且不显示整行?

问题描述

我有一个.listStyle(InsetGroupedListStyle())风格的 SwiftUI 列表。在此列表中,我在一个部分中有一些图像。

我想contextMenu在图像中添加一个。但是,它可以正常工作,而不是仅显示contextMenu附加的图像 - 显示整行,并且仅在该部分的顶部或底部行上圆角。

如何contextMenu仅显示图像,以及如何在所有情况下为所有角落获得圆角?

List {
    Section {
        // In this top row only the top two corners have rounded corners.
        Image("topImage")
            .resizable()
            .scaledToFit()
            .frame(width: 100, height: 100)
            .contentShape(RoundedRectangle(cornerRadius: 16, style: .continuous))  // this has no effect
            .contextMenu(ContextMenu(menuItems: {
                Button {
                    Text("Button")
                } label: {
                    HStack {
                        Text("Button Action")
                    }
                }
            }))
        
        // In this middle row none of the corners have rounded corners
        Image("middleImage")
            .resizable()
            .scaledToFit()
            .frame(width: 100, height: 100)
            .contentShape(RoundedRectangle(cornerRadius: 16, style: .continuous))  // this has no effect
            .contextMenu(ContextMenu(menuItems: {
                Button {
                    Text("Button")
                } label: {
                    HStack {
                        Text("Button Action")
                    }
                }
            }))
        // In this bottom row only the bottom corners have rounded corners
        Image("bottomImage")
            .resizable()
            .scaledToFit()
            .frame(width: 100, height: 100)
            .contentShape(RoundedRectangle(cornerRadius: 16, style: .continuous))  // this has no effect
            .contextMenu(ContextMenu(menuItems: {
                Button {
                    Text("Button")
                } label: {
                    HStack {
                        Text("Button Action")
                    }
                }
            }))
    }
}
.listStyle(InsetGroupedListStyle())  

标签: iosswiftswiftuicontextmenu

解决方案


推荐阅读