Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI ForEach refresh makes view pop

Tags:

swift

swiftui

I have something like this:


import SwiftUI

struct Overview: View {

    @ObservedObject var firstArray = FirstArray()

    var body: some View {
        Group{
            ScrollView(){
                ForEach(self.firstArray.array, id: \.self){ array in
                    SubView(array: array)
                }
                Spacer()
            }
        }.navigationBarTitle("Overview")
    }
}


struct SubView: View {

    @State var array

    var body: some View {
           NavigationLink(destination: DetailInfo(array: array){
                Image(systemName: "pencil.circle").resizable().frame(width: 30, height: 30)
            }
    }.navigationBarTitle("SubView")
}


struct DetailInfo: View {

    @State var array

    var body: some View {
        List(){
            ForEach(0..<self. array.count, id: \.self){item in
                Text(item)
            }.onDelete(perform: deleteItem)
        }
    }

    func deleteItem(at offsets: IndexSet) {
       self.array.remove(atOffsets: offsets)
    }

}

When I delete an item in the DetailInfo it pops me back to the Overview. Why is that? Is that because of the ForEach "refreshing" in the Overview. How can I stay on the DetailInfo ? When leaving out the id: \.self in Overview it doesn't show this behaviour.

like image 854
Simon Avatar asked Oct 23 '25 17:10

Simon


1 Answers

yes, it is because everything gets refresh and so the detail view and the navigationlink won't exist anymore and so the app "jumps" back to the root view

the "normal" solution is: do not delete the item in the detail view but in the list - then there is no problem and you got a nice animation for free from SwiftUI too

like image 122
Chris Avatar answered Oct 26 '25 08:10

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!