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)

Friday, December 20, 2013

iOS Get App Window

So, you want to get the iOS app window, huh?

Terminology is one of the great barriers to moving from language-to-language and platform-to-platform, so its no surprise that some people are going to want to search for different terms, so we cover a few cases in this post, just to make sure we're getting the answer you're actually after:

Case #1, you're really wanting to get the current UIViewController displayed in your application:

A. When you're using a NavigationController

  // Way #1: Get the topmost ViewController (current) in this navigation hierarchy.
  UIViewController *currentViewController = [[self.navigationController viewControllers] lastObject];

  // Way #2: Ask your UINavigationController which ViewController is the visible one.
  UIViewController *currentViewController = self.navigationController.visibleViewController;

B. When you're not (presumably nested modal views or other)

- (UIViewController *) getTopViewController
{
  UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;

  UIViewController *viewController = keyWindow.rootViewController;
  while(viewController.presentedViewController){
    viewController = viewController.presentedViewController;
  }
  
  return viewController;
}

Case #2: You actually want the key window:

  UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;

... which is a window that "manages and coordinates the views an app displays on the device screen", and of which your app probably only has one.

Case #3: What you really want is the UIView of the current UIViewController so you can manipulate it somehow, in which case you want to do:

  // I am in a UIViewController, so I can get my view like this
  UIView *view = [self view];

Well, hopefully that covers it, but if not, please leave a comment on a case we might have missed. Thanks, and please give us a +1 if you have the inclination!




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