SwiftUI Previews —Is there an easy way to visualize all different UI variations?

Guven James B
Swift2Go
Published in
2 min readFeb 15, 2020

Yes, that should be possible via Visual Stress Tests!

SwiftUI hot reload is a powerful tool for making sure that your views look pixel perfect. It also helps you to visualize how things will look under different environments (dark mode, accessibility, etc…). The super fast feedback cycle is a great help for making sure that your UI looks slick for all of your user base.

The regular way to visualize your user interface is through the PreviewProvider protocol. By adopting this protocol and providing a value for its static var previews {get} field, SwiftUI renders your UI in the preview pane. The very default setup looks like:

You would ideally want to see your new View on different devices, layouts and enviroments. That would make it easier to spot any UI problems before it reaches to your users. To do that, you simply provide different variations of your view for the previews field:

The problem with this approach is that you have to provide such variations for each of your views. That means a lot of copy paste code across your views. To prevent that, I have put together a PreviewFactory struct that takes in your view and spits out different variations of your view. That way, you can write the preview creation code once and use it across all your views. Here is how it looks:

You can find the code in GitHub Gist and use it in your own projects. It would be great to add more variations here so that all different environments are covered.

To use the PreviewFactory class from your views, simply call it as follows:

static var previews: some View {
PreviewFactory.previews(forView: MyCustomView())
}

Below you see an example. You get all those variations free without any code duplication. This will hopefully let you stress test your UI (only visually + manually) and let you know if there are any problems with it!

--

--