Utilizing PreviewModifier to construct a previewing atmosphere – Donny Wals

0
33
Utilizing PreviewModifier to construct a previewing atmosphere – Donny Wals


Revealed on: July 10, 2024

Xcode 16 and iOS 18 include a function that permits us to construct elaborate preview environments utilizing a brand new PreviewModifier protocol. This protocol permits us to outline objects that may create a single context or atmosphere that’s cached and used throughout your SwiftUI previews.

That is helpful as a result of it implies that you possibly can, for instance, populate a database with a bunch of mock knowledge that’s then utilized in your previews.

You can too use PreviewModifier to use particular styling to your previews, to wrap all of them in a particular wrapper, and extra.

Basically, they’re a software that permits you to configure your previews constantly throughout the board.

Adorning views utilizing PreviewModifier

The PreviewModifier protocol specifies two strategies which you can implement:

  • A static makeSharedContext technique
  • An occasion technique known as physique

The physique occasion strategies is handed the view that’s being previewed and a Context. This context can both be an object that you just created in makeSharedContext or Void should you don’t implement makeSharedContext.

For this instance, let’s assume that you just went forward and didn’t implement makeSharedContext. In a scenario like that, we will use PreviewModifier to brighten a view for our previews. For instance, we might wrap it in one other view or apply some styling to it.

I’m fairly positive that you just’re extra artistic than me so I’m simply going to go forward and present you the way you’d apply a orange background to your previewed view. Yeah, I do know… very artistic. The purpose is to indicate you the way to do that so as to do one thing a lot smarter than what I’m describing right here.

struct OrangeBackground: PreviewModifier {
    func physique(content material: Content material, context: Void) -> some View {
        content material
            .padding()
            .background {
                RoundedRectangle(cornerRadius: 16)
                    .fill(.orange)
            }
    }
}

#Preview(traits: .modifier(OrangeBackground())) {
    Textual content("Good day, world!")
}

Let’s have a look at the PreviewModifier first, after which I’ll clarify how I utilized it to my preview.

The modifier is outlined as a struct and I solely carried out the physique operate.

This operate is padded Content material which is no matter view the #Preview macro is getting used on (on this case, Textual content), and it receives a context. On this case Void as a result of I didn’t make a context.

The content material argument could be styled, modified, and wrapped nevertheless you want. It’s a view so you are able to do issues like give it a background, remodel it, alter its atmosphere, and far rather more. Something you are able to do with a view inside a View physique you are able to do right here.

The primary distinction is that you just’re receiving a totally instantiated occasion of your view. Meaning you possibly can’t inject new state or bindings into it or in any other case modify it. You’ll be able to solely apply view modifiers to it.

This brings us to our subsequent function of PreviewModifier making a context to supply mocked knowledge and extra.

Utilizing PreviewModifier to inject mock knowledge

To inject mock knowledge into your previews by means of PreviewModifier all you have to do is implement the makeSharedContext technique from the PreviewModifier protocol. This technique is static and is named as soon as for all of your previews. Which means the context that you just create on this technique is reused for your entire previews.

In follow that is good as a result of it means you get constant mock knowledge in your previews with out the overhead of recreating this knowledge incessantly.

Right here’s what a pattern implementation for makeSharedContext appears to be like like:

struct MockDataSource {
    // ...
}

struct OrangeBackground: PreviewModifier {
    static func makeSharedContext() async throws -> MockDataSource {
        return MockDataSource()
    }
}

On this case, I’m creating an occasion of some knowledge supply in my makeSharedContext technique. This MockDataSource would maintain all mocks and all knowledge for my views which is nice.

Nevertheless, the one approach for us to essentially use that mock knowledge in our view is by including our knowledge supply (or the mocked knowledge) to our previewed view’s atmosphere.

struct OrangeBackground: PreviewModifier {
    static func makeSharedContext() async throws -> MockDataSource {
        return MockDataSource()
    }

    func physique(content material: Content material, context: MockDataSource) -> some View {
        content material
            .atmosphere(.dataSource, context)
    }
}

Since we will’t make a brand new occasion of our content material, we will’t inject our mock knowledge supply instantly into the view by means of its initializer. The one approach we will get the info supply to the view is by including it to the atmosphere.

This isn’t very best for my part, however the design is sensible.

I’m additionally fairly positive that Apple designed this API with mocking SwiftData databases in thoughts and it will work nice for that.

On high of getting to make use of the atmosphere, the PreviewModifier solely works in tasks that focus on iOS 18 or later. Not an enormous drawback however it will have been good if utilizing Xcode 16 was ok for us to have the ability to use this helpful new API.

LEAVE A REPLY

Please enter your comment!
Please enter your name here