
タップしたりなぞったりして四角を画面上に配置して遊ぶiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@interface ViewController ()
@property (nonatomic, strong) NSMutableArray *tapLayer;
@property (nonatomic, strong) NSMutableArray *moveLayer;
@property (nonatomic, weak) CALayer *current;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
[self createTapLayers];
[self createMoveLayers];
}
– (void)createTapLayers
{
self.tapLayer = [NSMutableArray array];
for (int i=0; i<20; i++) {
float x = (i%4) * 80 + 10;
float y = (i/4) * 80 + 60;
CALayer *l = [CALayer layer];
l.frame = CGRectMake(x, y, 60, 60);
l.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1].CGColor;
l.opacity = 0;
[self.view.layer addSublayer:l];
[self.tapLayer addObject:l];
}
}
– (void)createMoveLayers
{
self.moveLayer = [NSMutableArray array];
for (int i=0; i<20; i++) {
float x = (i%4) * 80;
float y = (i/4) * 80 + 50;
CALayer *l = [CALayer layer];
l.frame = CGRectMake(x, y, 80, 80);
l.backgroundColor = [UIColor orangeColor].CGColor;
l.opacity = 0;
[self.view.layer addSublayer:l];
[self.moveLayer addObject:l];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
[self.tapLayer enumerateObjectsUsingBlock:^(CALayer *l, NSUInteger idx, BOOL *stop) {
CGRect rect = CGRectInset(l.frame, –10, –10);
if (CGRectContainsPoint(rect, p)) {
if (l.opacity != 0) {
l.opacity = 0;
} else {
l.opacity = 0.8;
}
}
}];
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
[self.moveLayer enumerateObjectsUsingBlock:^(CALayer *l, NSUInteger idx, BOOL *stop) {
CGRect rect = CGRectInset(l.frame, 0, 0);
if (CGRectContainsPoint(rect, p) && l != self.current) {
if (l.opacity != 0) {
l.opacity = 0;
} else{
l.opacity = 0.4 + (arc4random() % 10) * 0.05;
}
self.current = l;
}
}];
}
@end