4
votes

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.

2

2 Answers

2
votes

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

-1
votes

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.