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 Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.