TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Fixing SwiftUI previews when passing a specific object in a fetch request.

Forums > SwiftUI

In my code I use a NavigationLink inside of a List to allow the user to drill down into different save data that they have created and I am retrieving with @FetchRequest. My preview works for the top level list by providing example data within the data controller and giving the preview access to it like this:

struct FilteredList_Previews: PreviewProvider {
    static var previews: some View {
        FilteredList(filter: "All").environment(\.managedObjectContext, DataController.preview.container.viewContext)
    }
}

The problem arises with the destination view to the navigation link. It's expecting an object to be past in that I can only get from a FetchRequest. This is lead me to attempting a solution like this:

struct ContentCard_Views_Previews: PreviewProvider {
    @FetchRequest var problems: FetchedResults<UserProblem>
    static var previews: some View {
        TitleCardView(problem: problems.first!)
            .environment(\.managedObjectContext, DataController.preview.container.viewContext)
    }
}

but as you can glean from the fact that I'm here it is not working with the error "Instance member 'problems' cannot be used on type 'ContentCard_Views_Previews'" on line 4.

Are there any good solutions to fix the PreviewProvider in this specific case? Do I need to abandon passing around specific parts of my FetchRequest and store the current selection in some sort of ViewModel, or is there a simpler way to provide example data?

P.S. ChorData not playing nice with a MVVM structure has been a huge headache if you have any advice on organizing code when interacting with this framework would be appreciated.

2      

The solution turns out to be providing a static variable containing an example inside my UserProblem. Which looked like this:

static var example = UserProblem(context: DataController.preview.container.viewContext)

Once this was implemented I could pass this example and to my previous provider i also no longer needed to include the environment as it only needed access to the example and nothing else.

struct ContentCard_Views_Previews: PreviewProvider {
    static var previews: some View {
        TitleCardView(problem: UserProblem.example)
    }
}

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.