SmartLogic Logo (443) 451-3001

The SmartLogic Blog

SmartLogic is a web and mobile product development studio based in Baltimore. Contact us for help building your product or visit our website to learn more about what we do.

iOS Development: How to Create a Lightbox Effect

February 20th, 2013 by

While working on an iOS development project for a client this past week, I ran into a problem with building a lightbox effect. The design called for lightboxing a dialog, this typically means dimming everything that is not part of the lightbox.

Below, I’ll outline the problems I faced, and how to get around them. You can find the code below implemented in a sample project on github.

My initial run at this was admittedly not well thought out, I used the UIViewController’s UIVIew as the superview, e.g.:

[UIView transitionWithView:self.view
                  duration:0.25
                   options:UIViewAnimationOptionsTransitionCrossDissolve
                animations:^{
                    [self.view addSubview:overlay];
                }
                completion:nil];

Of course, once you run this you can see the problem, the controller view is under the navigation bar:

Overlay as subview of UIViewController's UIView

Our overlay is under the navigation and tab bars.

The tricky part is getting a full-screen overlay, including covering up navigation, tab and tool bars. In the case of a UINavigationController you can present the view as a subview of the UINavigationController view:

[UIView transitionWithView:self.navigationController.view
                  duration:0.25
                   options:UIViewAnimationOptionsTransitionCrossDissolve
                animations:^{
                    [self.navigationController.view addSubview:overlay];
                }
                completion:nil];

This will add the overlay on top of the Navigation Bar, but if you have a tab bar (which I didn’t, but I’m throwing it in), you’re still not quite there:

Overlay as subview of UINavigationController's UIView

Our overlay is still under the tab bar.

If your navigation controller is a component of a UITabBarController then the tab bar will still be visible, you will have to access the UITabBarController:

[UIView transitionWithView:self.tabBarController.view
                  duration:0.25
                   options:UIViewAnimationOptionsTransitionCrossDissolve
                animations:^{
                    [self.tabBarController.view addSubview:overlay];
                }
               completion:nil];
Overlay as subview of UITabBarController's UIView

The desired effect.

And there we go, a properly implemented lightbox effect on iOS.

Comment and let me know if you’ve solved this problem in a different way, or if you try my method and it works for you.

 

Add SmartLogic to your Google+ circles  for more like this.