カードをタッチすると、「ピっ」という感じで他のカードが上下にずれます。タッチしたカードにはそのカードの色の名前を書いておいて、この色の名前はなにかな〜?という感じで子供と遊んでみましょう。という感じのiPhoneアプリを作ってみます。
動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。
ポイント
カードのViewにtagを上から連番でふっておいて、タッチしたViewよりtagが小さいものは、上にスライドするように、大きいものは下にスライドするようにという計算をUITapGestureの中で書いてみました。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController () {
UIView *selected;
NSMutableArray *cards;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self createCards];
}
– (void)createCards
{
cards = [[NSMutableArray alloc] init];
UIColor *c1 = [UIColor redColor];
UIColor *c2 = [UIColor blueColor];
UIColor *c3 = [UIColor greenColor];
UIColor *c4 = [UIColor yellowColor];
UIColor *c5 = [UIColor purpleColor];
UIColor *c6 = [UIColor brownColor];
UIColor *c7 = [UIColor orangeColor];
NSArray *colors = @[c1, c2, c3, c4, c5, c6, c7];
NSArray *name = @[@”red”,@”blue”,@”green”,@”yellow”,@”purple”,@”brown”,@”orange”];
for (int i=0; i<7; i++) {
UIView *card = [[UIView alloc] initWithFrame:CGRectMake(0, 75 * i, 320, 568)];
card.backgroundColor = colors[i];
card.layer.cornerRadius = 20;
card.tag = i;
[self.view addSubview:card];
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(100, 160, 120, 50)];
l.backgroundColor = [UIColor clearColor];
l.text = name[i];
l.font = [UIFont fontWithName:@”Chalkduster” size:35];
l.textAlignment = NSTextAlignmentCenter;
l.textColor = [UIColor whiteColor];
[card addSubview:l];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(open:)];
[card addGestureRecognizer:tap];
[cards addObject:card];
}
}
– (void)open:(UIGestureRecognizer*)gr
{
// reset
if (selected) {
for (UIView *v in cards) {
[UIView animateWithDuration:0.3 animations:^{
v.transform = CGAffineTransformIdentity;
}];
}
selected = nil;
return;
}
// open
selected = gr.view;
float top = gr.view.frame.origin.y – gr.view.tag * 20;
[UIView animateWithDuration:0.3 animations:^{
// selected card
gr.view.transform = CGAffineTransformMakeTranslation(0, -top);
// other cards
for (UIView *v in cards) {
if (v.tag < gr.view.tag) {
float top = v.frame.origin.y – v.tag * 20;
v.transform = CGAffineTransformMakeTranslation(0, -top);
} else if (v.tag > gr.view.tag) {
float top = (568.0 – v.frame.origin.y) – ([cards count] – v.tag + 1) * 20;
v.transform = CGAffineTransformMakeTranslation(0, top);
}
}
}];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end