litbe
litbe

Reputation: 509

Why is the parent view's onDisappear() automatically invoked by the SwiftUI framework?

In the code below, if I click a row, Hello, in the List, the List's onDisappear() is invoked, as indicated by the trace, onDisappear called!. Is this expected?

I have some logic that needs to be executed when the List view is dismissed by an explicit action from the users. Thus, such an auto-invocation of onDisappear() would be problematic for me, if not accounted for.

Is it possible to prevent the framework from auto-invoking onDisappear for the parent view?


import SwiftUI
import SwiftData

struct DebugOnDisappear: View {
    var body: some View {
        UnexpectedOnDisappear()
            .onDisappear() {
                print("onDisappear called!")
            }
    }
    
    struct UnexpectedOnDisappear: View {
        @Query private var sbEntries: [SafeBoxEntryModel] = []
        
        var body: some View {
            VStack {
                List {
                    ForEach (sbEntries) { sbEntry in
                        NavigationLink("Hello") {Text("Hello")}
                    }
                }
            }
        }
    }
}

Screenshot for listing

List of "Hello"s

Screenshot for trace output

Trace output: "onDisappear called"

Upvotes: 0

Views: 106

Answers (0)

Related Questions