我有一个显示产品图片和一些基本信息的列表。
当用户点击特定的产品图像时,它实际上会显示一个上下文菜单,用于执行“保存图像”等操作。
以下是我所拥有的简化示例代码。
Image("imageofProduct1")
.contextMenu {
Button("Save", action: {
// Proceed with save function for Product 1
})
}
因为我可能在应用程序的不同部分有产品图像。有没有办法让我创建一个通用的上下文菜单,它将显示相同的“保存”操作,但也能够接受感兴趣的图像的名称。
目前,我可以将上下文菜单移动到以下位置:
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
}
}
和使用
更新:(使用 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 !!
关于generics - SwiftUI 通用上下文菜单 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61505039/