大きい順にならべてあそぶiPhoneアプリのサンプルコードを描いてみます。
動かすとこんな感じです
サンプルコード
#import “ViewController.h”
@interface ViewController ()
@property (nonatomic, weak) UIView *firstSelect;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.8 alpha:1.0];
[self createNodes];
}
– (void)createNodes
{
NSArray *seed = @[@(1), @(2), @(3), @(4), @(5)];
NSArray *rand = [self shuffle:seed];
for (int i=0; i<5; i++) {
int s = [rand[i] intValue] * 10 + 10;
UIView *node = [[UIView alloc] initWithFrame:CGRectMake(0, 0, s, s)];
node.tag = [rand[i] intValue];
node.center = CGPointMake(i * 80 + 80, 250 – CGRectGetMidY(node.bounds));
node.backgroundColor = [UIColor greenColor];
[self.view addSubview:node];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[node addGestureRecognizer:tap];
}
}
– (void)tap:(UITapGestureRecognizer*)gr
{
if (!self.firstSelect) {
self.firstSelect = gr.view;
} else {
[UIView animateWithDuration:0.1 animations:^{
CGPoint p = gr.view.center;
gr.view.center = CGPointMake(self.firstSelect.center.x, gr.view.center.y);
self.firstSelect.center = CGPointMake(p.x, self.firstSelect.center.y);
} completion:^(BOOL finished) {
[self check];
}];
self.firstSelect = nil;
}
}
– (void)check
{
int x = 0;
for (int i=1; i<=5; i++) {
UIView *v = [self.view viewWithTag:i];
if (x > v.center.x) {
return;
} else {
x = v.center.x;
}
}
UILabel *l = [[UILabel alloc] init];
l.text = @”Clear!”;
l.font = [UIFont boldSystemFontOfSize:40];
l.textColor = [UIColor greenColor];
l.transform = CGAffineTransformMakeRotation(-M_PI * 0.05);
[l sizeToFit];
l.center = CGPointMake(CGRectGetMidX(self.view.bounds), 100);
[self.view addSubview:l];
[UIView animateWithDuration:2.0 animations:^{
l.alpha = 0;
} completion:^(BOOL finished) {
[l removeFromSuperview];
[self restart:@(5)];
}];
}
– (NSArray*)shuffle:(NSArray*)origin
{
NSMutableArray *copy = [origin mutableCopy];
for (NSUInteger i = 0; i < [origin count]; i++) {
NSInteger n = arc4random_uniform([origin count] – i) + i;
[copy exchangeObjectAtIndex:i withObjectAtIndex:n];
}
return copy;
}
– (void)restart:(NSNumber*)n;
{
int count = [n intValue];
if (count == 0) {
return;
}
NSArray *seed = @[@(1), @(2), @(3), @(4), @(5)];
NSArray *rand = [self shuffle:seed];
for (int i=0; i<5; i++) {
[UIView animateWithDuration:0.2 animations:^{
UIView *v = [self.view viewWithTag:i + 1];
v.center = CGPointMake([rand[i] intValue] * 80, v.center.y);
}];
}
[self performSelector:@selector(restart:) withObject:@(count-1) afterDelay:0.2];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end