I am working on some SwiftUI and 1 of my NavigationLinks is causing an infinite loop, and I am unsure why.
First, I have this as my code.
First screens body
:
var body: some View {
List {
viewA
}
.listStyle(.insetGrouped)
.navigationTitle(viewModel.game.teamName)
.navigationBarTitleDisplayMode(.inline)
}
NavigationLink code:
private var viewA: some View {
CustomNavigationLink {
ViewAView(viewModel: viewModel.viewAViewModel)
} label: {
Text("View A")
}
}
The view model created for the scorecard manager:
var viewAViewModel: ScorecardManagerViewModel {
ViewAViewModel(game: game)
}
The init for the ViewA view model:
init(game: Game) {
self.game = game
self.scenarios = game.scenariosAsArray() ?? []
shouldShowInitialAddScenario()
updateCampaignScore()
print("VIEW A INIT")
}
My custom NavigationLink is just a view that takes a destination. This is used throughout the app and has no issues for any other view:
struct CustomNavigationLink<Destination, Label>: View where Destination : View, Label : View {
var destination: () -> Destination
let label: () -> Label
var body: some View {
HStack {
label()
Spacer()
Image(systemName: "chevron.right")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 7)
.fontWeight(.bold)
.foregroundColor(.purple)
}
.background(
NavigationLink {
destination()
} label: {
Text("")
}
.opacity(0)
)
}
}
I have tried removing all observability from ViewAView and the ViewAViewModel, and the init is still being called. Not really sure why this is causing an infinite loop.
As a note, this is only happening on my phone running 18.2.1, but it doesn't happen on the iOS 18.0 simulator.
UPDATE It looks like if I move the creation of the view model in the init of the first screen, this is no longer an issue. It was previously a computed var.