In the learning content for iOS 16 and SwiftUI, it is shown that
struct ContentView: View {
var body: some View {
NavigationStack {
List(1..<50) { i in
NavigationLink(value: i) {
Label("Row \(i)", systemImage: "\(i).circle")
}
}
.navigationDestination(for: Int.self) { i in
Text("Detail \(i)")
}
.navigationTitle("Navigation")
}
}
}
This infers the use of a simple Hashable or Equatable model, as inferred, since this example uses native types.
In my case, something I had developed for iOS 15, no longer works when I migrate my view hierarchy to NavigationStack
. Specificially, as shown below (this code is now broken). How can I adapt my code to work with the new NavigationStack & NavigationLink paradigms?
I don't see how I can easily make my SwiftUI views, which require use of ObservedObjects (could also be derived from StateObjects, but that's neither here nor there for the question), adapt to the new NavigationLink
usage specified in iOS 16.
This is my minimally producible example:
struct ContentView: View {
var body: some View {
NavigationStack {
ProfileView()
// there is other logic for other root views, but
// this problem can just focus on ProfileView in NavigationStack
}
}
}
struct ProfileView: View {
@ObservedObject var progressViewModel = ProgressViewModel()
@ObservedObject var challengesViewModel = ChallengesViewModel()
@ObservedObject var subscriptionViewModel = SubscriptionViewModel()
var body: some View {
VStack {
// Below is the code that is broken, and I'm not sure how to adapt it
// to the new iOS 16 navigation patterns since I am not reusing the same view
// as in the above example
NavigationLink(destination: ProgressView(progressViewModel: self.progressViewModel)) {
Text("User progress nav link")
}
NavigationLink(destination: ChallengesView(challengesViewModel: self.challengesViewModel)) {
Text("Challenges nav link")
}
NavigationLink(destination: SubscriptionView(subscriptionViewModel: self.subscriptionViewModel)) {
Text("Subscription nav link")
}
}
}
}
struct ProgressView: View {
@ObservedObject var progressViewModel: ProgressViewModel
var body: some View {
VStack {
Text(progressViewModel.overallUserProgressString)
}
}
}
struct ChallengesView: View {
@ObservedObject var challengesViewModel: ChallengesViewModel
var body: some View {
VStack {
Text(challengesViewModel.numberOfChallengesPerformedString)
}
}
}
struct SubscriptionView: View {
@ObservedObject var subscriptionViewModel: SubscriptionViewModel
var body: some View {
VStack {
Text(subscriptionViewModel.localSubscriptionPriceString)
}
}
}