UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out 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.