我有一个显示产品图片和基本信息的列表。
[当用户点击特定的产品图片时,它实际上会显示一个上下文菜单,用于执行诸如“保存图片”等操作。
以下是我所拥有的简化示例代码。
Image("imageofProduct1")
.contextMenu {
Button("Save", action: {
// Proceed with save function for Product 1
})
}
因为我可能在应用程序的不同部分中具有产品图像。有没有一种方法可以创建通用的ContextMenu,该菜单将显示相同的“保存”操作,但也可以接受感兴趣的图像的名称。
当前,我可以将上下文菜单移至以下位置:
func ContextMenuContent() -> some View {
return Button("Save") {
// Save function of the image
}
}
在主体中,我可以显示相同的上下文菜单:
Image("imageofProduct1")
.contextMenu(menuItems: ContextMenuContent)
如果我要将ContextMenu函数移到一个单独的文件中。对于封装,我是否可以以某种方式传入图像名称,以便基于提供的图像名称执行图像保存功能?
方法可以如下
func ContextMenuContent(_ imageName: String) -> some View {
return Button("Save") {
// Save function of the image
// use imageName here
}
}
和用法
Updated:(已通过Xcode 11.4测试)
// it does not matter how it get here
let imageName = "imageofProduct1"
//...
Image(imageName) // or same constant here and below
.contextMenu { ContextMenuContent(imageName) } // here !!