Skip to content

Instantly share code, notes, and snippets.

@exorcyze
Last active January 4, 2021 16:12
Show Gist options
  • Save exorcyze/f5cd1ce25f72f508e494c3c13e7e6977 to your computer and use it in GitHub Desktop.
Save exorcyze/f5cd1ce25f72f508e494c3c13e7e6977 to your computer and use it in GitHub Desktop.
//
// UIViewController+Preview.swift
// Created : Mike Johnson, 2020
//
import Foundation
import UIKit
import SwiftUI
// Source: https://www.swiftbysundell.com/articles/getting-the-most-out-of-xcode-previews/
//
// ViewController Usage:
/*
@available(iOS 13, *)
struct MyViewControllerPreview: PreviewProvider {
static var previews: some View {
MyViewController(data: mydata).asPreview()
}
}
*/
// View Usage:
/*
#if canImport(SwiftUI) && DEBUG
import SwiftUI
@available(iOS 13, *)
struct TestView_Preview: PreviewProvider {
static var previews: some View {
TestView().asPreview()
}
}
#endif
*/
// MARK: - UIViewController extensions
extension UIViewController {
@available(iOS 13, *)
private struct Preview: UIViewControllerRepresentable {
var viewController: UIViewController
func makeUIViewController(context: Context) -> UIViewController {
viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
// No-op
}
}
@available(iOS 13, *)
func asPreview() -> some View {
Preview(viewController: self)
}
}
// MARK: - UIView Extensions
extension UIView {
@available(iOS 13, *)
private struct Preview: UIViewRepresentable {
var view: UIView
func makeUIView(context: Context) -> UIView {
view
}
func updateUIView(_ view: UIView, context: Context) {
// No-op
}
}
@available(iOS 13, *)
func asPreview() -> some View {
Preview(view: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment