Skip to content

Instantly share code, notes, and snippets.

@AppleBetas
Last active April 26, 2017 17:45
Show Gist options
  • Save AppleBetas/3c54deee540d85c5f6d7acebb6b233b8 to your computer and use it in GitHub Desktop.
Save AppleBetas/3c54deee540d85c5f6d7acebb6b233b8 to your computer and use it in GitHub Desktop.
UIViewController+CurrentViewController.swift - Get the actual currently displaying view in your app
//
// 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
}
}
}
@AppleBetas
Copy link
Author

You can call this in many ways, and it'll get the frontmost view controller in your app. This means that even if you have a modal view controller, being presented by another view controller, after another view controller, in a navigation controller, inside a tab bar controller, it'll get the first view controller, the one that the user actually sees.

Examples

Get app's frontmost view controller

UIApplication.shared.currentViewController

Get window's frontmost view controller

window.currentViewController

Get view controller's frontmost view controller (assuming self is a UIViewController or one of it's subclasses)

self.currentViewController

@AppleBetas
Copy link
Author

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.

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