Craig Grummitt – Before I forget

Discoveries in Swift and iOS development.

,

Holy cow – You can preview UIKit code live in Xcode!

·

Now that SwiftUI is feeling more and more established since WWDC 2020, I’m in the process of getting properly acquainted with it. In my exploring I discovered something actually more relevant to UIKit that blew me away. (and it’s been around since 2019!)

So you can use SwiftUI code to preview UIKit objects live – UIViewControllers or UIViews – from within Xcode 😲, in the canvas.

Here’s how – first UIViewController:

Let’s say you have a UIViewController subclass ViewController.

  • Step 1: In the Storyboard (let’s assume Main) give your view controller a storyboard ID. Let’s say ‘ViewController’.
  • Step 2: Head over to your ViewController.swift file. Make the ViewController class final:

[sourcecode language=”javascript”]
final class ViewController: UIViewController {
[/sourcecode]

  • Step 3: Import SwiftUI:

[sourcecode language=”javascript”]
import SwiftUI
[/sourcecode]

  • Step 4: Again, in your ViewController.swift file, create an extension for ViewController, implementing the  UIViewControllerRepresentable protocol, with its two required functions:

[sourcecode language=”javascript”]
extension TermsViewController: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> ViewController {
}
func updateUIViewController(_ uiViewController: ViewController, context: Context) {
}
}
[/sourcecode]

We can ignore the updateUIViewController function as this is used by a SwiftUI parent to update the model data of the view controller.

  • Step 5: Return our View Controller from the makeUIViewController function. We can do this with the UIStoryboard.instantiateViewController function.

[sourcecode language=”javascript”]
func makeUIViewController(context: Context) -> ViewController {
UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(
withIdentifier: "ViewController") as! ViewController
}
[/sourcecode]

  • Step 6: Set up a preview provider that returns your View Controller as a preview:

[sourcecode language=”javascript”]
struct ViewControllerPreviews: PreviewProvider {
static var previews: some View {
ViewController()
}
}
[/sourcecode]

Just like that, BAM, the canvas appears to the right of the ViewController, and within it, your view controller as it would appear in the simulator. But that’s not all – press the play button to the bottom right of the ViewController, and a live version of your view controller will actually run, right there in a panel next to your code, just as if it were SwiftUI. Holy cow!

Oh – and one more thing – if you want to preview a UIView rather than a UIViewController it’s pretty straightforward – just extend your custom view class with UIViewRepresentable rather than UIViewControllerRepresentable!

 


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *