Hi,
say I have a List. Each entry in the List is a NaviagtionLink, which has the same View (NextView) as the destination. I want NextView to display a different random number each time I navigate to that view and I want give this number as a parameter to NextView. How would I do that?
(Of course, this is a contrived example to illustrate the issue, what I really want to do is inject a newly generated CoreData child managed context each time a navigation happens.)
(Please see the code sample at the end of the post.
If I just use NavigationLink(destination: NextView(n: Int.random(in: 0 ... 9))) it will always show the same number, because NextView[...] will be evaluated only, if the "outer" view body is evaluated.
NavigationLink(destination: NextView(n: Int.random(in: 10 ... 20)), isActive: $showEdit) somehow retriggers the "outer" view body evaluation, so I get a new random number each time. But this seems like a hack.
Ideally there would be a way, that evaluate NextView at the point in time when the navigation happens, but I can't think of a way to do this.
Thanks in advance for any ideas, pointers, hints on what's wrong and how it should be done right ;-)
Cheers, Michael
import SwiftUI
struct ContentView: View {
@State var showEdit = false
var body: some View {
NSLog("ContentView Body")
return
NavigationView {
List {
NavigationLink(destination: NextView(n: Int.random(in: 10 ... 20)), isActive: $showEdit) {
Text("With binding")
}
NavigationLink(destination: NextView(n: Int.random(in: 0 ... 9))) {
Text("Without binding")
}
}
}
}
}
struct NextView: View {
var n: Int
init(n: Int) {
self.n = n
NSLog("init: \(n)")
}
var body: some View {
NSLog("Next View body")
return
VStack {
Text("Next View - What else")
Text("** \(n) **")
}
}
}
func getNew(number: Int) -> TheObject {
let obj = TheObject(number: number)
NSLog("getNew \(obj.number)")
return obj
}
class TheObject: ObservableObject {
@Published var number: Int
init(number: Int) {
self.number = number
}
deinit {
NSLog("Deinit \(self.number)")
}
}