![](/img/trans.png)
[英]SwiftUI LazyVGrid NavigationLink has unusual animation on return
[英]SwiftUI NavigationLink in LazyVGrid picking random index
每次選擇一行時,系統決定將隨機索引轉發到下一個視圖。
下面是代碼:
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
}
}
}
}
}
}
您應該使用標准的 NavigationLink 功能,它會自動將其轉換為按鈕 - 您實際上並不需要 .background 和 .onTapGesture。
ForEach(1...10, id: \.self) { index in
NavigationLink(
destination: TestDetail(index: index),
label: {
Text("\(index)")
})
.accentColor(.primary)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.