Skip to content

Instantly share code, notes, and snippets.

@StanislavK
Created December 30, 2021 17:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StanislavK/5b37e7ab115933e2546ab8051219d885 to your computer and use it in GitHub Desktop.
Save StanislavK/5b37e7ab115933e2546ab8051219d885 to your computer and use it in GitHub Desktop.
import SwiftUI
struct GenericUIViewControllerRepresentable<ViewControllerType>: UIViewControllerRepresentable
where ViewControllerType: UIViewController {
let factory: (Context) -> ViewControllerType
func makeUIViewController(context: Context) -> ViewControllerType {
factory(context)
}
func updateUIViewController(
_ uiViewController: ViewControllerType,
context: Context
) {}
}
@StanislavK
Copy link
Author

Usage:

struct ViewController_Preview: PreviewProvider {
    static var previews: some View {
        GenericUIViewControllerRepresentable { _ in
            return ViewController()
        }
    }
}

@StanislavK
Copy link
Author

For old legacy code add:

#if canImport(SwiftUI) && DEBUG
.
.
.
#endif

@StanislavK
Copy link
Author

  • also:
#if canImport(SwiftUI) && DEBUG
import SwiftUI

let deviceNames: [String] = [
    "iPhone SE",
    "iPhone 11 Pro Max"
]

struct ViewController_Preview: PreviewProvider {
    static var previews: some View {
        ForEach(deviceNames, id: \.self) { deviceName in
            GenericUIViewControllerRepresentable { _ in
                ViewController()
            }
            .previewDevice(PreviewDevice(rawValue: deviceName))
            .previewDisplayName(deviceName)
        }
    }
}
#endif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment