How to use SwiftUI to Speed Up your View Coding

Leonardo Souza
3 min readJun 20, 2019
Photo by Kelly Sikkema on Unsplash

So if you're here, you definitely want to use SwiftUI in your current project. Unfortunately the complete migration in some cases, are close to impossible, but maybe SwiftUI can help us spark a little of joy in our day to day ⌘+R, to check out our awesome UI, that we created using view code (because we're cool kids 😎, who likes to build and run our projects 72 times a hour).

There's no, maybe, SwiftUI is here to to save us!

If you are able to migrate to the newer Xcode 11 (ATM in Beta) and is using macOS Catalina (ATM in Beta), all you need to do is import SwiftUI to your UIKit ViewController and with some quick setup, you'll be able to see your ViewController's view written with view code, in the SwiftUI preview panel.

Enough! We don't wanna waste any more time building our projects and reading this introduction! Let's do this!

First, you'll need to bump your deployment target to 13.0 while using SwiftUI API's, don't worry the time you will waste to change it back afterwards, trust me, it's worthy.

First, import SwiftUI in your view controller.

Second, let's write our ViewController code with plain old UIKit

And now comes the magic 🧙‍♂️. We need to create a representation of this UIKit ViewController in SwiftUI, this is where UIViewControllerRepresentable protocol comes in to action, basically it will make our ViewController "Presentable" to SwiftUI preview. To do this, create a struct that conforms with UIViewControllerRepresentable and add it at end of ViewController's file. After, you must override updateUIViewController and makeUIViewController functions, as their names suggests, the former is to update your UI (ifNeeded), and the latter is to create an instance of your ViewController.

Now that our view controller is is able to represented in SwiftUI's preview, let's setup the preview itself. Right after the struct that we just created, add another struct, but this time conforming with the protocol PreviewProvider, that will create a preview environment for us. The PreviewProvider protocol requires previews static variable, which is expecting a View, and the ViewControllerRepresentable that we just created is one 😊, so just return a new instance ViewControllerRepresentable.

And we're done!

Stop right there cowpoke ✋! I know you hit, or was preparing your thumb and index finger to hit ⌘+B or ⌘+R. But we no longer belong to that life 🤠. Open the Xcode SwiftUI preview window and press ⌥+⌘+P to run preview.

That’s all folks! :)

--

--

Leonardo Souza

Software Engineer @iFood & Machine Learning Enthusiast 🤖