Member-only story
SwiftUI Preview: How to Preview UIKit ViewControllers in Real-Time
Unlock Real-Time Previews of UIKit ViewControllers with SwiftUI’s Powerful Preview Tool
In this article, we’ll walk through how to create a simple UIViewController using SnapKit and preview it with SwiftUI. This setup is useful if you're developing for iOS and want to leverage SwiftUI's live previews, even though your views are UIKit-based. Here’s the code, explained step-by-step, and a few tips on how to preview UIKit views in SwiftUI.
This can be used for iOS 13 and above.
Step 1: Create the UIViewController
Our MakeViewController is a simple subclass of UIViewController that has a UILabel centered in the view. We use SnapKit, a popular layout library, to set up constraints:
class MakeViewController: UIViewController {
private lazy var makeLabel: UILabel = {
let label = UILabel()
label.text = "Make"
label.textColor = .red
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(makeLabel)
makeLabel.snp.makeConstraints { make in
make.center.equalToSuperview()
}
}
}- UILabel Initialization: The
UILabelis created as a lazy property. By usinglazy var, we delay its…
