【问题标题】:SwiftUI Generic ContextMenu viewSwiftUI 通用 ContextMenu 视图
【发布时间】:2020-04-29 15:05:18
【问题描述】:

我有一个显示产品图片和一些基本信息的列表。

当用户点击特定的产品图片时,它实际上会显示一个上下文菜单,用于“保存图片”等操作。

以下是我所拥有的简化示例代码。

    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 函数移动到单独的文件中。对于封装,我是否可以以某种方式传入图像的名称,以便根据提供的图像名称执行图像保存功能?

【问题讨论】:

    标签: generics swiftui contextmenu


    【解决方案1】:

    方法可以如下

    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 !!
    

    【讨论】:

    • 这个解决方案就像一个魅力,对我的原始代码进行了一些语法更新。非常感谢您的 hrlp!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2020-08-05
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 2022-06-10
    • 2021-09-13
    相关资源
    最近更新 更多