Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Wednesday, July 31, 2013

Get the Current ViewController in iOS

So, you want to get the topmost ViewController in iOS, eh?

It turns out that there is no straightforward function to obtain the current, top view controller. This is another weird case of Apple being good at constraining you, but bad at helping you. Fortunately, as with many of these hangups, the solution isn't too horrendous as you will see below.

Why do you want to get the current view anyway? Maybe its because you just received a push notification and you want to render a view on the current screen (the "active view"). Whatever your need, this method will be the step in the right direction.

Lets look at the code.

+ (UIViewController*) getTopController
{
    UIViewController *topViewController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

Hey, that's not too bad... but why this approach? Well, this approach is slightly different than other approaches you may have come across in your search for the solution. It differs because it is useful in just about every type of hierarchical view structure, whether you have a NavigationController in the loop or not.






About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates