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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.