Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mingsai/9eab95b9b0c99bf1a04c0b4fe17aee5b to your computer and use it in GitHub Desktop.
Save mingsai/9eab95b9b0c99bf1a04c0b4fe17aee5b to your computer and use it in GitHub Desktop.
Using UIViewController via the SwiftUI Environment
//
// UIViewController+SwiftUI.swift
//
// Created by Timothy Costa on 2019/07/04.
// Copyright © 2019 timothycosta.com. All rights reserved.
//
import SwiftUI
struct ViewControllerHolder {
weak var value: UIViewController?
}
struct ViewControllerKey: EnvironmentKey {
static var defaultValue: ViewControllerHolder { return ViewControllerHolder(value: UIApplication.shared.windows.first?.rootViewController ) }
}
extension EnvironmentValues {
var viewController: UIViewController? {
get { return self[ViewControllerKey.self].value }
set { self[ViewControllerKey.self].value = newValue }
}
}
extension UIViewController {
func present<Content: View>(style: UIModalPresentationStyle = .automatic, @ViewBuilder builder: () -> Content) {
let toPresent = UIHostingController(rootView: AnyView(EmptyView()))
toPresent.rootView = AnyView(
builder()
.environment(\.viewController, toPresent)
)
self.present(toPresent, animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment