1

I have this code:

import SwiftUI
import Combine

struct ContentView: View {
let items = [
    Item(name: "Name 1"),
    Item(name: "Name 2"),
    Item(name: "Name 3")
]

var body: some View {
    NavigationView {
        List {
            ForEach(items, id: \.name) { item in
                NavigationLink(
                    destination: DetailView(name: item.name),
                    label: {
                        Text(item.name)
                    })
            }
        }
    }
}
}

struct DetailView: View {
var name: String

var body: some View {
    Text(name)
}

init(name: String) {
    self.name = name
    
    print("Initializing detail view for \(self.name)")
}
}

struct Item {
let name: String
}

And it prints out the initializing print out for each of the 3 items.

In my real application, I don't want the detail views to be initialized until the user clicks on the navigation link, because I will be doing API calls in the detail view's initializer, and so I don't want it to be automatically called for each item.

  • Does this answer your question https://stackoverflow.com/a/61743337/12299030? – Asperi Nov 21 '20 at 08:56
  • Hmmm, I just wrapped my DetailView in a DeferView, but it says it can't find DeferView in scope. Running Xcode 12.2 and iOS 14.2 simulator. Edit: Ah, I see. DeferView is a custom struct. Thank you, I think this will do. –  Nov 21 '20 at 09:02
  • It look like DeferView fits the content. Is there a way to make it fit the parent? –  Nov 21 '20 at 19:42

0 Answers0