SwiftUI NavigationLink 立即导航回来 [英] SwiftUI NavigationLink immediately navigates back
问题描述
我正在使用 SwiftUI
在 NavigationView 中创建从行到详细视图的 NavigationLinks
(类似于教程 https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation).但是,当我在我的应用程序中进行测试时,NavgiationLink 在被点击后会立即从详细视图导航回上一个视图(详细视图仅显示一秒钟).
I am using SwiftUI
to create NavigationLinks
from rows to detail views in a NavigationView (similar to what is being done in the tutorial https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation). However, when I test in my app, the NavgiationLink immediately navigates back from the detail view to the previous view after being tapped (the detail view only shows up for only a second).
代码如下:
struct ItemsView: View {
var body: some View {
NavigationView {
VStack {
List {
ForEach(Query.items) { item in
NavigationLink(destination: ItemDetail(item: item)) {
ItemRow(item: item)
}
}
}
Spacer()
}
.navigationBarTitle(Text("Items"))
}
}
}
private struct ItemRow: View {
var item: Item
var body: some View {
VStack(alignment: .leading) {
Text(item.title)
.font(.headline)
item.completionDate.map({
Text("Created ($0.shortDateTime)")
})
item.completionDate.map({
Text("Active (Date().offsetString(from: $0)) ago")
})
}
}
}
struct ItemDetail: View {
var item: Item
var body: some View {
VStack {
Text("(item.title)")
Text("(String(describing: item.creationDate))")
Text("(String(describing: item.completionDate))")
Text("(item.complete)")
}
.navigationBarTitle(Text("Item"), displayMode: .inline)
}
}
Query
是使用 Realm
完成的:
let realm = try! Realm()
class Query {
static let items = realm.objects(Item.self)
}
这似乎是从 realm.objects(Item.self)
返回的 Results
对象的问题.当我使用 let items = [Item(), Item()]
然后调用 ForEach(items) { ... }
对静态数据进行尝试时,导航起作用了正如预期的那样.
It seems like this could be a problem with the Results<Item>
object that is return from realm.objects(Item.self)
. When I tried it with static data using let items = [Item(), Item()]
and then calling ForEach(items) { ... }
, the navigation worked as expected.
推荐答案
通过将 ForEach(Query.items)
更改为 ForEach(Array(Query.items))
使数据静态化.
Fixed it by changing ForEach(Query.items)
to ForEach(Array(Query.items))
to make the data static.
这篇关于SwiftUI NavigationLink 立即导航回来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!