Wednesday, April 15, 2009

Putting a background behind a UIView transition


When doing a setAnimationTransition: with a UIView, you can do a "flip left/right" or a "curl up/down". If you do a flip left/right, you'll usually see a blank black screen "behind" the view as it flips. (The built-in Stocks app does this.) Recently someone asked me if you could have something else back there, and I thought "huh, that's interesting, I never tried that" and we investigated. It turns out that you can, but you have to set up the view stack properly.

So let's say we have 3 UIView objects, frontView, backView, and rootView. Before the transition begins, frontView is a visible subview of rootView and backView is not yet in the view stack. You begin an animation block and then (usually) do [frontView removeFromSuperview] followed by [rootView addSubview:backView], then commit the animation block and watch the animation take place. You might think that adding another subview of rootView, one that sits below frontView, would make that view be visible behind the animation during the transition. At least, that's what I thought, but it doesn't work. I'm not sure why, but it seems that rootView and all of his subviews become "invisible" during the transition.

But, but! if you put another UIView under rootView, that view will be visible during the transition. Maybe in your project, your views are already set up that way. But if frontView and backView are immediate subviews of the main window, then of course nothing can be below the main window, and you'll need to interpose another UIView object into your view stack.

Instead of posting sample code, I'm going to suggest downloading the LocateMe sample app from ADC. It's already designed with a "main" view and a "flipside" view who are subviews of a root view, and the root view is a subview of the main window. Get the project, open the MainWindow.xib, and add a UIImageView (for example) in the main window:


Make sure the toggleView method is using UIViewAnimationTransitionFlipFromLeft(Right) in its animation block (it doesn't make sense with the curl up/down animation) and then build and run the project.

1 comment:

Anonymous said...

Thanks - that was really useful. I've been trying to figure this one out for hours!