Search code examples
iosswiftswiftuirealmcrud

SwiftUI realm database Issue passing the fetched data to another view


I'm using realm database and I had issue after fetching for the data for a list and use on tap gesture property to go to the detail view it's only show the first set of data in my realm database. I will show some pictures to illustrate. enter image description here

this is how my list look like

enter image description here

and this is detail view when clicked and it's only showing the first set of data whatever what you clicked on.

 ForEach(realmManger.patterns, id: \.id) { userPattern in
                                
patternCell(title: userPattern.title ?? "Error??", date: userPattern.dateCreated ?? Date.now)
.onTapGesture {
 editPattern = true
}.sheet(isPresented: $editPattern) {
patternEdit(userPattern: userPattern)
  .environmentObject(realmManger)
  }
}

the code is too long I tried to show what important

struct patternEdit: View {
    
    @EnvironmentObject var realmManger:RealmManger
    @State var showAlert = false
    
    let userPattern:Patterns
    
    var body: some View {
   
                Text(userPattern.title ?? "Error")
                    .font(.title)
                    .foregroundColor(Color("lightBlue"))
                    .padding()

}

and this is the code for the detail view why is it only showing the first data ?


Solution

  • Take the .sheet() out of the ForEach loop and use the .sheet(item: ...), like in this example code using @State var selectedPattern: ...

     @State var selectedPattern: Patterns?  // <-- here
     // ...
     
     var body: some View {
         // ...
         ForEach(realmManger.patterns, id: \.id) { userPattern in
             patternCell(title: userPattern.title ?? "Error??", date: userPattern.dateCreated ?? Date.now)
                 .onTapGesture {
                     selectedPattern = userPattern  // <-- here
                 }
         }
         .sheet(item: $selectedPattern) { userPattern in  // <-- here
             patternEdit(userPattern: userPattern)
                 .environmentObject(realmManger)
         }
     // ...
     }
     
    

    Adjust the example code to suit your purpose.