通过单击 LazyVGrid 中的项目切换到另一个视图

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

我想通过单击 LazyGrid 中的某个项目来实现切换到另一个视图。我该怎么做?我附上 LazyGrid 的代码

据我了解,应该使用 NavigationLink 和 onTapGesture 来完成,但我不确定具体该怎么做。我尝试过不同的教程,但我不太确定如何将它们与我的代码结合起来

struct LazyGridView: View {
        
    let columns = Array(repeating: GridItem(.flexible(minimum: 20)), count: 3)
    var body: some View {
        ScrollView{
            LazyVGrid(columns: columns) {
                ForEach(MockData.colors, id: \.self) {
                    RoundedRectangle(cornerRadius: 10)
                        .fill($0.gradient)
                        .frame(height: 110)
                        .contextMenu{
                            Button("Edit item"){
                                
                            }
                            Button("Delete item"){
                                
                            }
                        
                        }
                }
                
                
            }
        
            .padding()
        }
    }
}
ios swift swiftui swiftui-navigationlink swiftui-ontapgesture
1个回答
0
投票

使用

NavigationStack
NavigationLink
NavigationPath
进行数据驱动的导航。 ADC 文档

示例:

struct DetailView: View {
    @Binding var path: NavigationPath
    let text: String
    
    var body: some View {
        VStack {
            Text("\(text)! Oh my!")
            Button {
                path.removeLast()
            } label: {
                Text("Back")
            }
        }
    }
}

struct ContentView: View {
    @State private var path = NavigationPath()
    let columns = Array(repeating: GridItem(.flexible(minimum: 20)), count: 3)
    @State private var animals = ["Lions", "Tigers", "Bears"]
    
    var body: some View {
        NavigationStack(path: $path) {
            LazyVGrid(columns: columns) {
                ForEach(animals, id: \.self) { animal in
                    RoundedRectangle(cornerRadius: 10)
                        .frame(height: 110)
                        .contextMenu{
                            NavigationLink(animal, value: animal)
                        }
                }
            }
            .navigationDestination(for: String.self) { textValue in
                DetailView(path: $path, text: textValue)
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.