
くるくる回っている四角いぴたっと合わせて遊ぶiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@interface ViewController ()
@property (nonatomic, strong) NSMutableArray *turnViews;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithWhite:0.97 alpha:1];
self.turnViews = [NSMutableArray array];
[self createViewOne];
[self createViewTwo];
[self createViewThree];
[self createViewFour];
[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
}
– (void)createViewOne
{
CGRect rect = CGRectMake(40, 50, 60, 60);
CGPoint anchor = CGPointMake(0.1, 0.1);
[self createView:rect anchor:anchor];
}
– (void)createViewTwo
{
CGRect rect = CGRectMake(130, 210, 100, 100);
CGPoint anchor = CGPointMake(0.5, 0.5);
[self createView:rect anchor:anchor];
}
– (void)createViewThree
{
CGRect rect = CGRectMake(180, 360, 40, 40);
CGPoint anchor = CGPointMake(0.1, 0.9);
[self createView:rect anchor:anchor];
}
– (void)createViewFour
{
CGRect rect = CGRectMake(60, 380, 30, 30);
CGPoint anchor = CGPointMake(0.5, 0.4);
[self createView:rect anchor:anchor];
}
– (void)createView:(CGRect)rect anchor:(CGPoint)anchor
{
UIView *shadow = [[UIView alloc] initWithFrame:rect];
shadow.backgroundColor = [UIColor blackColor];
[self.view addSubview:shadow];
UIView *v = [[UIView alloc] initWithFrame:rect];
v.backgroundColor = [UIColor orangeColor];
[self.view addSubview:v];
shadow.layer.anchorPoint = anchor;
v.layer.anchorPoint = anchor;
[self.turnViews addObject:v];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
[self.turnViews enumerateObjectsUsingBlock:^(UIView *v, NSUInteger idx, BOOL *stop) {
CGRect rect = [v.layer.presentationLayer frame];
if(CGRectContainsPoint(rect, p))
v.tag = (v.tag) ? 0 : 1;
}];
}
– (void)tick:(NSTimer *)sender
{
[self.turnViews enumerateObjectsUsingBlock:^(UIView *v, NSUInteger idx, BOOL *stop) {
if (v.tag == 0) {
v.transform = CGAffineTransformRotate(v.transform, M_PI * 0.03);
}
}];
}
@end