通过上下文菜单 SwiftUI“弹出”时展开图像

问题描述 投票:0回答:1

我正在尝试实现按住图像时在“照片”应用程序中获得的功能。出现一个上下文菜单,其中包含各种选项(复制、共享、收藏夹等),但我试图复制的主要内容是图像从网格扩展到更大尺寸的版本。

这就是我想要实现的目标:

这就是我的应用程序目前所做的:

我的应用程序的代码如下

let columns = [
    GridItem(.adaptive(minimum: 100), spacing: 2),
    GridItem(.adaptive(minimum: 100), spacing: 2),
    GridItem(.adaptive(minimum: 100), spacing: 2),
    GridItem(.adaptive(minimum: 100), spacing: 2),
    GridItem(.adaptive(minimum: 100), spacing: 2)
]


var body: some View {
    ScrollView {
        LazyVGrid(columns: columns, spacing: 2) {
            ForEach(imageUrls, id: \.self) { imageUrl in
                AsyncImage(url: imageUrl) { image in
                    image
                        .resizable()
                        .aspectRatio(1, contentMode: .fill)
                        .contextMenu {
                            Button {
                                print("Save image")
                            } label: {
                                Label("Save to Photos", systemImage: "square.and.arrow.down")
                            }

                        }
                } placeholder: {
                    ProgressView()
                }
            }
        }
    }

我考虑过可能需要跟踪图像是否处于“上下文菜单模式”状态,如果是,则增加尺寸,但是我认为这会弄乱网格,我不确定是否可以跟踪这样的状态。

如有任何帮助,我们将不胜感激。

swift swiftui contextmenu swiftui-image
1个回答
0
投票

首先,由于我没有您的图像数据,所以我无法与您的代码分享我的答案。我正在展示一个我为回答您的问题而制作的示例。

您可以通过

contextMenu
选项使用
preview
上的修饰符。

当您长按视图项时,

preview
基本上会返回一个新视图。所以你可以展示任何你想要的东西。

您只需要显示更大尺寸的视图即可。您可以通过多种方式做到这一点。我正在展示一个例子:

import SwiftUI

struct ContentView: View {
    var image: some View {
        Image(systemName: "sun.max.fill")
            .resizable()
            .padding()
            .background(.cyan)
            .foregroundStyle(.orange)
            
    }
    var body: some View {
        image
            .frame(width: 200, height: 200)
            // Here is your real answer
            .contextMenu {
                Button(action: {
                }) {
                    Label("Save", systemImage: "square.and.arrow.up")
                }
                Button(action: {
                }) {
                    Label("Edit", systemImage: "square.and.arrow.up")
                }
            } preview: {
               // I used `withAnimation` so that the change looks smooth
               // I'm just showing an increased size image inside preview
                withAnimation {
                    image
                        .frame(width: 400, height: 400)
                }
            }
    }
}

模拟:

© www.soinside.com 2019 - 2024. All rights reserved.