Using SwiftUI Previews to speed up development isn’t exclusive to SwiftUI. It’s fairly easy to use SwiftUI Previews in UIKit, but it can be made even easier with the inclusion of a few extensions.
public extension UIView {
private struct Preview: UIViewRepresentable {
let view: UIView
func makeUIView(context: Context) -> some UIView { view }
func updateUIView(_ uiView: UIViewType, context: Context) { }
}
var preview: some View { Preview(view: self) }
}
public extension UIViewController {
private struct Preview: UIViewControllerRepresentable {
let viewController: UIViewController
func makeUIViewController(context: Context) -> UIViewController { viewController }
func updateUIViewController(_ uiViewController: UIViewController, context: Context) { }
}
var preview: some View { Preview(viewController: self) }
}
Using this extension, creating a preview for a given UIKit view or view controller is as simple as:
struct MyView_Preview: PreviewProvider {
static var previews: some View {
MyView().preview
}
}
For views that require configuration:
struct MyView_Preview: PreviewProvider {
static var previews: some View {
let view = MyView()
// configure view
return view.preview
}
}