0

I'm trying to get the currently displayed ViewController using the following:

let currentViewController = UIApplication.sharedApplication().keyWindow!.rootViewController?.presentedViewController

This property gives me the TabBarController. The only property after presentedViewController is "childViewControllers".

How could I use this to attain the currently displayed ViewController?

Shobhakar Tiwari
  • 7,862
  • 4
  • 36
  • 71
Faisal Syed
  • 921
  • 1
  • 11
  • 25
  • 1
    Possible duplicate of [Get the current displaying UIViewController on the screen in AppDelegate.m](http://stackoverflow.com/questions/11637709/get-the-current-displaying-uiviewcontroller-on-the-screen-in-appdelegate-m) – JAB Oct 14 '16 at 18:53

2 Answers2

0

If it is TabBar based Application then to check which is currently selected ViewController depends on following condition :

  1. First Track which tabbar is selected e.g :Condition to check which Tab Index is selected

  2. Maintain NavigationController for each TabBar

  3. Then Check navigationcontroller stack last index to match up the ViewController . ( which is chilviewcontroller you can say).

Hope it helps .

Shobhakar Tiwari
  • 7,862
  • 4
  • 36
  • 71
0

You can access the selected view controller from the tabBarController. An easy way to do so is with this extension.

Just take note that it will not update with the correct value until viewDidAppear. Checking the property prior to that will give you your previous screen.

import UIKit

extension UITabBarController {
    var displayedViewController: UIViewController? {
        return selectedViewController
    }
}
CodeBender
  • 35,668
  • 12
  • 125
  • 132