【问题标题】:SwiftUI NavigationLink in LazyVGrid picking random indexLazyVGrid 中的 SwiftUI NavigationLink 选择随机索引
【发布时间】:2022-05-28 00:41:48
【问题描述】:

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

请观看以下视频进行说明:

下面是代码:

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)")
    }
}

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    您一次激活所有链接(因为所有链接都取决于一种状态)。相反,对于这种情况,我们需要使用不同的 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
                            }
                    }
                }
            }
        }
    }
    

    backup

    【讨论】:

    • 谢谢。这件事让我的大脑嘎嘎作响了好几个小时。
    【解决方案2】:

    您应该使用标准 NavigationLink 功能,它会自动将其转换为按钮 - 您实际上并不需要 .background 和 .onTapGesture。

                    ForEach(1...10, id: \.self) { index in
                        NavigationLink(
                            destination: TestDetail(index: index),
                            label: {
                                Text("\(index)")
                            })
                            .accentColor(.primary)
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 2023-04-07
      • 1970-01-01
      相关资源
      最近更新 更多