简体   繁体   中英

SwiftUI navigation link does not load

When clicking on the navigation link in my SwiftUI application, the screen freezes and I can see the memory doubing every second - almost getting to a 1GB of memory before I terminate the application.

I have a simple navigation link as follows:

NavigationLink {
    FeedbackView(viewModel: .init())
} label: {
    HStack {
        Label("Feedback", systemImage: "bubble.left.circle")
            .fontWeight(.semibold)
        Spacer()
        Image(systemName: "chevron.right")
    }
}

Upon clicking on this navigtion link, the screen does not go to the next view and instead freezes. I am unable to tap anything else in the iOS simulator. The memory skyrockets and continues to do so until I stop the application.

The view model is it initializing in the FeedbackView call is as follows.

import Foundation
import Dependencies

class FeedbackViewModel: ObservableObject {

}

The view is below.

import SwiftUI

struct FeedbackView: View {
    @ObservedObject var viewModel: FeedbackViewModel

    var body: some View {
        Text("loaded feedback")
    }
}

If I remove .init() from the FeedbackView call within the NavigationLink, and instead initialize the FeedbackViewModel in the FeedbackView itself, I also get the same issue. I am rather new to iOS development and am not sure of which xCode tools to use that could help me diagnose this bug.

First: use @StateObject instead:

struct FeedbackView: View {
    @StateObject var viewModel: FeedbackViewModel

    var body: some View {
        Text("loaded feedback")
    }
}

Why: unlike @ObservedObject , @StateObject won't get destroyed and re-instantiated every time the view struct redraws. Never create @ObservedObject from within the view itself ( Check this article for more details )

Second: how to initialize the @StateObject ? Really depends on your use case, but you could do this:

struct FeedbackView: View {
    ...
    init(_ providedViewModel: ViewModel = ViewModel()) {
        _viewModel = StateObject(wrappedValue: providedViewModel)
    }
...

The "special notation" _viewModel refers to actual property wrapped inside StateObject property wrapper.

This way parent can either pass the model in (if there's some data it needs to initialize), or let the default model to be created:

NavigationLink {
    FeedbackView()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM