最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swift - Infinite View Loop - SwiftUI - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论