NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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()
    }
}

1      

Nice but you will need to add

#if DEBUG
...
#endif

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

2      

@cgaaf  

Great point!

1      

Hacking with Swift is sponsored by Stream

SPONSORED Build Chat messaging quickly with Stream Chat. The Stream iOS Chat SDK is highly flexible, customizable, and crazy optimized for performance. Take advantage of this top-notch developer experience, get started for free today!

Click here

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.