ばらばらに表示された、あいうえをの5文字を「あ」から順番にタッチで消していくiPhoneアプリを描いてみます。けせる文字をタッチしたら音が鳴るようにしています。
動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property int count;
@property (strong, nonatomic) NSMutableArray *words;
@property (nonatomic,strong) AVAudioPlayer *mySound;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
[self createWords];
}
#define AIUEO @[@“あ“, @“い“, @“う“, @“え“, @“お“]
– (void)createWords
{
for (int i=0; i<30; i++) {
float x = (i % 5) * 60 + 10;
float y = (i / 5) * 60 + 50;
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 60, 60)];
l.backgroundColor = [UIColor clearColor];
l.text = [AIUEO objectAtIndex:arc4random() % 5];
l.textColor = [UIColor blackColor];
l.font = [UIFont systemFontOfSize:50];
[self.view addSubview:l];
l.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(check:)];
[l addGestureRecognizer:tap];
if (!self.words) {
self.words = [[NSMutableArray alloc] init];
}
[self.words addObject:l];
}
}
– (void)check:(UIGestureRecognizer*)gr
{
NSString *target = [AIUEO objectAtIndex:self.count];
if ([target isEqual:[(UILabel*)gr.view text]]) {
// sound
[self sound:self.count];
[UIView animateWithDuration:0.2 animations:^{
gr.view.transform = CGAffineTransformMakeScale(0.1, 0.1);
} completion:^(BOOL finished) {
[gr.view removeFromSuperview];
[self.words removeObject:gr.view];
BOOL next = YES;
for (UILabel *l in self.words) {
if ([l.text isEqual:target]) {
next = NO;
}
}
if (next) {
self.count = (self.count + 1) % 5;
// comp check
if ([self.words count] == 0) {
[self reset];
}
}
}];
}
}
– (void)reset
{
[self performSelector:@selector(createWords) withObject:Nil afterDelay:1.0];
}
– (void)sound:(int)i
{
NSArray *names = @[@”A”,@”i”,@”u”,@”e”,@”o”];
NSString *fileName = [names objectAtIndex:i];
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:@”m4a”]];
self.mySound = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
self.mySound.volume = 0.5;
[self.mySound setVolume:1.0];
[self.mySound play];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end