Neil Macy

UI Previews in Xcode 15

Apple keeps reminding us that the best way to write new apps is with SwiftUI. But for those of us who are working on existing apps, UIKit is often still the reality.

SwiftUI has had previews in Xcode from the start. It's a great feature, because it helps you see your UI code while you're writing it. You can sort of get it working with UIKit too, but it's a bit hacky and it never feels to me like it's meant to work.

Now, Previews support UIKit and SwiftUI equally well, with the new #Preview macro. (This also simplifies creating previews on SwiftUI, which makes me happy.) Here's how to create a preview of a UIViewController:

#Preview {
    MyViewController()
}

And here's how to create a preview of a SwiftUI View:

#Preview {
    MyView()
}

Really simple, and there's no difference between SwiftUI and UIKit. Really cool to see!

This code below contains two previews, a SwiftUI one and a UIKit one. You can have these side by side in the same file and it works nicely.

import UIKit
import SwiftUI

class MyViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let label = UILabel(frame: view.bounds)
        label.text = "Hello, world!"
        label.font = UIFont.preferredFont(forTextStyle: .title1)
        label.textAlignment = .center
        view.addSubview(label)
    }
}

struct MyView: View {
    var body: some View {
        VStack {
            Text("Hello, world!")
                .font(.title)
        }
        .padding()
    }
}

#Preview("UIKit") {
    MyViewController()
}

#Preview("SwiftUI") {
    MyView()
}

Published on 7 June 2023