每次选择一行时,系统都会决定将随机索引转发到下一个视图。
下面是代码:
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)
您一次激活所有链接(因为所有链接都取决于一种状态)。相反,我们需要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)
| 归档时间: |
|
| 查看次数: |
1438 次 |
| 最近记录: |