触る位置によって、ビューの反転のアニメーションを変える

2-9 レシピ:ビューの反転

FlipViewをinitしたら、黄色と青色の背景のふたつのビューを作成して、それらを交互に反転させる。ただし、アニメーションはタップした位置によって変えてみる。

@interface FlipView : UIView {

}

@end

@implementation FlipView

-(id)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	
	UIView *view1 = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	UIView *view2 = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	view1.backgroundColor = [UIColor yellowColor];
	view2.backgroundColor = [UIColor blueColor];
	
	[self addSubview:view1];
	[self addSubview:view2];
	
	return self;
}


-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	CGPoint pt = [[touches anyObject] locationInView:self];
	
	UIViewAnimationTransition trans = UIViewAnimationTransitionNone;
	// うえの方をたたくと上へ、したの方を叩くと下に
	if (pt.y < 20) {
		trans = UIViewAnimationTransitionCurlUp;
	} else {
		if (pt.y > 440) {
			trans = UIViewAnimationTransitionCurlDown;
		}
	}
	
	
	// 極端に上でも下でもない場合には、左右で決める
	if (trans == UIViewAnimationTransitionNone) {
		if (pt.x < 160) {
			trans = UIViewAnimationTransitionFlipFromRight;
		} else {
			trans = UIViewAnimationTransitionFlipFromLeft;
		}
	}
		
	CGContextRef cont = UIGraphicsGetCurrentContext();
	[UIView beginAnimations:nil context:cont];
	
	// どう動かすかを決定する
	[UIView setAnimationTransition:trans
						   forView:[self superview]
							 cache:YES];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationDuration:1.0];
	
	[self exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
	
	[UIView commitAnimations];
	
}
@end