Mobile App Development

iOS Development: How to Create a Lightbox Effect

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.

 

You've successfully subscribed to SmartLogic Blog
Great! Next, complete checkout for full access to SmartLogic Blog
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.