Forked from timothycosta/UIViewController+SwiftUI.swift
Created
September 23, 2019 01:18
-
-
Save mingsai/9eab95b9b0c99bf1a04c0b4fe17aee5b to your computer and use it in GitHub Desktop.
Using UIViewController via the SwiftUI Environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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