[英]SwiftUI NavigationLink immediately navigates back
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 ).我正在使用
SwiftUI
创建从行到NavigationLinks
中的详细视图的 NavigationLinks(类似于教程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).但是,当我在我的应用程序中进行测试时,NavgiationLink 在被点击后立即从详细视图导航回上一个视图(详细视图仅显示一秒钟)。
Here's the code:这是代码:
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)
}
}
The Query
is done using Realm
: Query
是使用Realm
完成的:
let realm = try! Realm()
class Query {
static let items = realm.objects(Item.self)
}
It seems like this could be a problem with the Results<Item>
object that is return from realm.objects(Item.self)
.这似乎是从
realm.objects(Item.self)
返回的Results<Item>
对象的问题。 When I tried it with static data using let items = [Item(), Item()]
and then calling ForEach(items) { ... }
, the navigation worked as expected.当我使用静态数据尝试使用
let items = [Item(), Item()]
然后调用ForEach(items) { ... }
,导航按预期工作。
通过将ForEach(Query.items)
更改为ForEach(Array(Query.items))
以使数据静态来修复它。
The reason is ForEach(Query.items, id: \\.self)
missing an identifier.原因是
ForEach(Query.items, id: \\.self)
缺少标识符。 When you add one hashable
or \\.self
.当您添加一个
hashable
或\\.self
。 the List should work like a charm.该列表应该像魅力一样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.