gpt4 book ai didi

ios - LazyVGrid 中的 SwiftUI NavigationLink 选择随机索引

转载 作者:行者123 更新时间:2023-12-01 23:42:51 25 4
gpt4 key购买 nike

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

请观看以下视频了解详情: enter image description here

代码如下:

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

最佳答案

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

关于ios - LazyVGrid 中的 SwiftUI NavigationLink 选择随机索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64756332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com