SwiftUI NavigationLink immediately navigates back

六眼飞鱼酱① 提交于 2020-06-27 17:58:05

问题


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).

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:

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). When I tried it with static data using let items = [Item(), Item()] and then calling ForEach(items) { ... }, the navigation worked as expected.


回答1:


Fixed it by changing ForEach(Query.items) to ForEach(Array(Query.items)) to make the data static.




回答2:


The reason is ForEach(Query.items, id: \.self) missing an identifier. When you add one hashable or \.self . the List should work like a charm.



来源:https://stackoverflow.com/questions/59671119/swiftui-navigationlink-immediately-navigates-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!