iPhone白黒床

白黒の床をスライドさせるiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor lightGrayColor];

    [self createPanels];

}

– (void)createPanels

{

    for (int i=0; i<25; i++) {

        float x = (i % 5) * 60 + 40;

        float y = (i / 5) * 60 + 80;

        UIView *panel = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];

        panel.tag = 1;

        panel.backgroundColor = (i%2) ? [UIColor blackColor] : [UIColor whiteColor];

        panel.center = CGPointMake(x, y);

        [self.view addSubview:panel];

    }

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    CGPoint p = [[touches anyObject] locationInView:self.view];

    UIView *hit = [self.view hitTest:p withEvent:nil];

    if (hit.tag == 1) {

        for (int j=0; j<4; j++) {

            float x = 60 * cos(M_PI * 0.5 * j) + hit.center.x;

            float y = 60 * sin(M_PI * 0.5 * j) + hit.center.y;

            UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];

            v.center = hit.center;

            v.backgroundColor = hit.backgroundColor;

            v.tag = 1;

            [self.view addSubview:v];

            [UIView animateWithDuration:0.3 animations:^{

                v.center = CGPointMake(x, y);

            }];

        }

        hit.backgroundColor = [hit.backgroundColor isEqual:[UIColor whiteColor]] ? [UIColor blackColor] : [UIColor whiteColor];

    }

}

@end