Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Navigation automatically closing/pop - Realm

I'm populating a List with a Realm Result set.

When navigating from this list it opens a new view then automatically closes that view.

Using a struct presents no issue.

Why would the second view automatically close?

I have a screen recording but cant post here.

import SwiftUI
import Combine

struct TestStruct:Identifiable{

    let id = UUID()
    let firstname: String
}

extension TestStruct {
    static func all() -> [TestStruct]{
        return[
            TestStruct(firstname: "Joe"),
            TestStruct(firstname: "Jane"),
            TestStruct(firstname: "Johns")
        ]
    }
}

struct TestListView: View {
    let realmList = Horoscope.getHoroscopes() //Fetches from Realm
    let structList = TestStruct.all()

    var body: some View {
        NavigationView{
            // This owrks
            //            List(structList) { item in
            //                MyItemRow(itemTxt: item.firstname)
            //            }

            //This automatically closes the view
            List(realmList) { item in
                MyItemRow(itemTxt: item.firstname)
            }
            .navigationBarTitle("Charts", displayMode: .automatic)
            .navigationBarItems(trailing: EditButton())
        }
    }
}


struct MyItemRow: View {

    var itemTxt:String

    var body: some View {
        NavigationLink(destination: Text("Test")) {
            Text(itemTxt)
        }
    }
}

struct TestListView_Previews: PreviewProvider {
    static var previews: some View {
        TestListView()
    }
}
like image 465
Yarm Avatar asked Oct 14 '19 12:10

Yarm


1 Answers

I think the answer can be found here

In short, do not generate the id of the collection on which the ForEach iterates. It would detect a change and navigate back.

Realm object has an auto generated id property with each reference, try replacing it with a consistent id

like image 97
gujci Avatar answered Sep 18 '22 13:09

gujci