LazyVGrid 中的 SwiftUI NavigationLink 选择随机索引

nis*_*ngh 3 ios swift swiftui

每次选择一行时,系统都会决定将随机索引转发到下一个视图。

请观看以下视频以进行澄清: 在此输入图像描述

下面是代码:

struct TestView: View {
    let columns = [
        GridItem(.flexible())
    ]
    @State var showDetail = false

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns, spacing: 20) {
                ForEach(1...10, id: \.self) { index in
                    Text("\(index)")
                        .background(NavigationLink(destination: TestDetail(index: index), isActive: $showDetail) {
                            EmptyView()
                        }).onTapGesture {
                            showDetail = true
                        }
                }
            }
        }
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

struct TestDetail: View {
    var index: Int
    var body: some View {
        Text("\(index)")
    }
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 6

您一次激活所有链接(因为所有链接都取决于一种状态)。相反,我们需要NavigationLink针对这种情况使用不同的构造函数。

这是固定变体。使用 Xcode 12.1 / iOS 14.1 进行测试

struct TestView: View {
    let columns = [
        GridItem(.flexible())
    ]
    @State var selectedItem: Int?

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns, spacing: 20) {
                ForEach(1...10, id: \.self) { index in
                    Text("\(index)")
                        .background(NavigationLink(destination: TestDetail(index: index), tag: index, selection: $selectedItem) {
                            EmptyView()
                        }).onTapGesture {
                            selectedItem = index
                        }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)