Previews in Xcode also work with UIKit!


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


This is a typical example of a SwiftUI View being displayed inside the preview canvas in Xcode 15:

But If you've written SwiftUI code before Xcode 15 was released, you might have noticed that the syntax to create a preview has changed a bit!

It used to be that you had to declare a struct that would conform to the protocol PreviewProvider

…but since Xcode 15, this syntax has changed because now we use the macro #Preview.

We give this macro a closure that returns a View and the macro takes care of displaying that View inside the preview canvas.

But what’s really cool with this new syntax is that it's no longer only limited to displaying a SwiftUI View in the preview canvas!

Now we can also return a UIKit UIView or UIViewController inside the closure that we pass to the #Preview and it will be displayed inside the preview canvas!

Here’s an example where I’m creating and returning a UILabel inside the closure, and as you can see the preview canvas indeed displays that UILabel ✌️

By the way, if your app has a minimum deployment target that’s less than iOS 17, you will see this error when returning a UIKit view from inside a #Preview.

Don’t worry, all you need to do is annotate the #Preview with @available(iOS 17, *) and the error will go away 😌

So don’t forget: as long as you're using Xcode 15, you can use a #Preview to easily see the content of a UIKit UIView or UIViewController controller without needing to launch your app inside a simulator or a real iOS device!

Here’s the code if you want to experiment with it:

import UIKit

@available(iOS 17, *) 
#Preview {
    let label = UILabel()
    label.text = "Hello, UIKit world!"
    return label
}
Previous
Previous

Here are 3 advanced tips in Swift 💡

Next
Next

Bad practice: not using a ButtonStyle