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

Ultimate Portfolio App - View Modifier for Previews idea

Forums > Articles

@cgaaf  

So I've started Paul's new Ultimate Portfolio App series.

Really enjoying the series so far. After finishing the "First steps in UI" article I realized that copying the code to add the DataController and CoreData each time would become repetative and cumbersome.

To make working with Previews a little more "DRY," I created a custom view modifier to add all of the DataController code. So far this seems to be working effectively. Let me know what you all think.

struct PreviewDataInjector: ViewModifier {
    let dataController = DataController.preview

    func body(content: Content) -> some View {
        content
            .environment(\.managedObjectContext, dataController.container.viewContext)
            .environmentObject(dataController)
    }
}

extension View {
    func previewDataController() -> some View {
        self.modifier(PreviewDataInjector())
    }
}

Then you can just use the view modifier to eliminate the boiler plate on previews.

struct ProjectsView_Previews: PreviewProvider {
    static var previews: some View {
        ProjectsView(showClosedProjects: false)
            .previewDataController()
    }
}

5      

Nice but you will need to add

#if DEBUG
...
#endif

around the struct and extension as Previews are only on Debug not Release

6      

@cgaaf  

Great point!

5      

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.