iPhoneコロコロ四角

白い線で描いた四角をコロコロ転がすだけのiPhoneアプリを描いてみます。


動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。

サンプルコード

#import “ViewController.h”

@interface ViewController ()

@property (strong, nonatomic) UIView *box;

@property (nonatomic) int current;

@property (nonatomic) int tapCount;

@property (nonatomic) BOOL isAnimating;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];

    [self createRoad];

    [self box];

    [self start];

}

– (void)countup

{

    self.tapCount++;

}

– (void)start

{

    [NSTimer scheduledTimerWithTimeInterval:2.0/60.0 target:self selector:@selector(tick:) userInfo:nil repeats:YES];

}

– (void)tick:(NSTimer*)sender

{

    if (self.current < self.tapCount && !self.isAnimating) {

        self.current ++;

        self.isAnimating = YES;

        

        float x = self.box.frame.origin.x + self.box.frame.size.width;

        float y = self.box.frame.origin.y + self.box.frame.size.height;

        self.box.layer.anchorPoint = CGPointMake(1.0, 1.0);

        self.box.layer.position = CGPointMake(x, y);

        [UIView animateWithDuration:1.0 animations:^{

            self.box.transform = CGAffineTransformMakeRotation(M_PI/2.0);

        } completion:^(BOOL finished) {

            self.box.transform = CGAffineTransformIdentity;

            self.box.frame = CGRectMake(self.box.frame.origin.x + 40, self.box.frame.origin.y, 40, 40);

            self.isAnimating = NO;

        }];

    }

}

– (void)createRoad

{

    UIView *road = [[UIView alloc] initWithFrame:CGRectMake(0, 190, 320, 3)];

    road.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:road];

}

– (UIView*)box

{

    if (!_box) {

        _box = [[UIView alloc] initWithFrame:CGRectMake(10, 150, 40, 40)];

        _box.backgroundColor = [UIColor blackColor];

        _box.layer.borderColor = [UIColor whiteColor].CGColor;

        _box.layer.borderWidth = 3;

        [self.view addSubview:_box];

        

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(countup)];

        [_box addGestureRecognizer:tap];

    }

    return _box;

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end