Flip between two views

Until now, when we have added a little view to a big view, the little view has remained in the big one. We will now swap out the little view and replace it with another little view while the app is running.

The big view contains an array of two little views, although only one of the little views is visible (i.e., currently added to the big view) at any given moment. The instance variable index in class BigView is the index in the array of the curently visible little view. It is initialized to 0 and flips back and forth between 0 and 1.

When the big view detects a touch, it changes the currently visible subview by calling transitionFromView:toView:duration:options:completion: and updates the index accordingly. The finger actually touches down inside of a little view. But the little views have no touchesEnded:withEvent: method, so the touchesEnded:withEvent: of the big view is called instead. The view that is rotated is the superview of the first argument of transitionFromView:toView:duration:options:completion:.

Source code in Flip.zip

Our classes LittleView0 and LittleView1 are very similar. But they don’t have to be. They could be totally different subclasses of UIView.

  1. main.m
  2. Class FlipAppDelegate
  3. Class BigView
  4. Class LittleView0
  5. Class LittleView1

Things to try

  1. The background behind the doors stays black regardless of the backgroundColor of the BigView. To change the background to yellow, we must change the background of the superview of the BigView, which is the window. Add the following statement to the application:didFinishLaunchingWithOptions: method of the application delegate.
    	self.window.backgroundColor = [UIColor yellowColor];

  2. Try UIViewAnimationOptionTransitionCurlUp or UIViewAnimationOptionTransitionCrossDissolve in place of UIViewAnimationOptionTransitionFlipFromLeft.

  3. Our program doesn’t actually detect a swipe at all. It detects merely the end of a touch. Make it detect a swipe, and distinguish between left, right, up, and down swipes as will do here. Then specify one of the options UIViewAnimationOptionTransitionFlipFromLeft, UIViewAnimationOptionTransitionFlipFromRight, UIViewAnimationOptionTransitionCurlUp, UIViewAnimationOptionTransitionCurlDown.

  4. Transition between three little views. Keep them in an array. Change
    	NSUInteger newIndex = 1 - index;	//toggle the index
    to the following. The % is the remainder operator.
    	NSUInteger newIndex = (index + 1) % views.count;	//cycle the index

  5. When we move from one little view to another, is the first little view removed from the big view or merely hidden somehow? Let’s print the number of elements in the big view’s array of subviews. Insert the following statement at the end of touchesEnded:withEvent:.
    	NSLog(@"self.subviews.count == %u", self.subviews.count);