Last active
April 26, 2017 17:45
-
-
Save AppleBetas/3c54deee540d85c5f6d7acebb6b233b8 to your computer and use it in GitHub Desktop.
UIViewController+CurrentViewController.swift - Get the actual currently displaying view in your app
This file contains hidden or 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+CurrentViewController.swift | |
| // | |
| // Created by AppleBetas on 2017-01-24. | |
| // Copyright © 2017 AppleBetas. All rights reserved. | |
| // | |
| import UIKit | |
| extension UIViewController { | |
| var currentViewController: UIViewController { | |
| get { | |
| if let presentedViewController = presentedViewController { | |
| return presentedViewController | |
| } | |
| return self | |
| } | |
| } | |
| } | |
| extension UINavigationController { | |
| override var currentViewController: UIViewController { | |
| get { | |
| if let viewController = visibleViewController { | |
| return viewController.currentViewController | |
| } | |
| return super.currentViewController | |
| } | |
| } | |
| } | |
| extension UITabBarController { | |
| override var currentViewController: UIViewController { | |
| get { | |
| if let viewController = selectedViewController { | |
| return viewController.currentViewController | |
| } | |
| return super.currentViewController | |
| } | |
| } | |
| } | |
| extension UISplitViewController { | |
| override var currentViewController: UIViewController { | |
| get { | |
| if let viewController = viewControllers.first { | |
| return viewController.currentViewController | |
| } | |
| return super.currentViewController | |
| } | |
| } | |
| } | |
| extension UIWindow { | |
| var currentViewController: UIViewController? { | |
| get { | |
| if let viewController = rootViewController { | |
| return viewController.currentViewController | |
| } | |
| return nil | |
| } | |
| } | |
| } | |
| extension UIApplication { | |
| var currentViewController: UIViewController? { | |
| get { | |
| if let window = self.keyWindow { | |
| return window.currentViewController | |
| } | |
| return nil | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add support for UISplitViewController.
How this works:
If two view controllers. are being displayed at once, it will choose the primary (leftmost) view controller. Otherwise, it'll work like normal.