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:
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:
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];
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.