如何点击LazyVGrid中的网格项并segue到另一个视图(本质上类似于集合视图)



我有我的代码设置如下:

var body: some View {

NavigationStack {
VStack {
// Contacts Scroll View
ScrollView {
LazyVGrid(columns: threeColumnGrid, spacing: 20) {
ForEach($contacts, id: .self) { $contact in
ContactCell(firstName: $contact.firstName.wrappedValue)
}
}.padding(EdgeInsets(top: 20,
leading: 20,
bottom: 20,
trailing: 20))
}
}.background(Color(CustomColors.background.rawValue))
}
}

我希望能够点击其中一个网格项目,以便segue进入另一个屏幕,但我能想出的唯一解决方案是NavigationLink,它只插入一个需要点击的链接。

我需要整个网格项目是可点击的,没有任何额外的文本作为链接。

旁注:我还研究了NavigationLink的isActive属性,它工作得很好,但这在iOS 16中被弃用了…这就好像苹果拒绝让我们使用swiftUI创建一个集合视图。

明白了。我使用:navigationDestination(ispresent:destination:)

见下面代码:

struct ContactsGridView: View {

@Binding var contacts: [Contact]
@State var shouldPresentContactMainView = false

let threeColumnGrid = [GridItem(.flexible(), spacing: 20),
GridItem(.flexible(), spacing: 20),
GridItem(.flexible(), spacing: 20)]

var body: some View {

NavigationStack {
VStack {
// Contacts Scroll View
ScrollView {
LazyVGrid(columns: threeColumnGrid, spacing: 20) {
ForEach($contacts, id: .self) { $contact in
ContactCell(firstName: $contact.firstName.wrappedValue)
.onTapGesture {
shouldPresentContactMainView = true
}
.navigationDestination(isPresented: $shouldPresentContactMainView) {
ContactMainView()
}
}
}.padding(EdgeInsets(top: 20,
leading: 20,
bottom: 20,
trailing: 20))
}
}.background(Color(CustomColors.background.rawValue))
}
}
}

最新更新