
同じマークのカードを全部めくるiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor brownColor];
[self createCards];
}
– (void)createCards
{
for (int i=0; i<72; i++) {
float x = (i % 9) * 34 + 24;
float y = (i / 9) * 34 * 1.414 + 80;
UIView *card = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30*1.414)];
card.backgroundColor = [UIColor whiteColor];
card.tag = arc4random() % 4 + 1;
card.center = CGPointMake(x, y);
card.layer.cornerRadius = 3;
card.layer.borderWidth = 1;
card.layer.borderColor = [UIColor grayColor].CGColor;
[self.view addSubview:card];
[card.layer addSublayer:[self cardBack]];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[card addGestureRecognizer:tap];
}
}
– (CALayer *)cardBack
{
UIBezierPath *path = [UIBezierPath bezierPath];
for (int i=0; i<8; i++) {
[path moveToPoint:CGPointMake(0, i * 4)];
[path addLineToPoint:CGPointMake(25, i * 4 + 6)];
[path moveToPoint:CGPointMake(0, i * 4 + 6)];
[path addLineToPoint:CGPointMake(25, i * 4)];
}
CAShapeLayer *l = [CAShapeLayer layer];
l.name = @”back”;
l.frame = CGRectMake(2.5, 2.5*1.414, 25, 25 * 1.414);
l.strokeColor = [UIColor greenColor].CGColor;
l.path = path.CGPath;
l.borderColor = [UIColor greenColor].CGColor;
l.borderWidth = 1;
return l;
}
– (void)tap:(UITapGestureRecognizer *)gr
{
[self flip:gr.view];
NSPredicate *findSameSuit = [NSPredicate predicateWithFormat:@”tag = %d”, gr.view.tag];
[[self.view.subviews filteredArrayUsingPredicate:findSameSuit] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * idx * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (gr.view != obj) {
[self flip:obj];
}
});
}];
}
– (void)flip:(UIView *)v
{
if ([[v.layer.sublayers[0] name] isEqual:@”back”]) {
[v.layer.sublayers[0] removeFromSuperlayer];
UILabel *l = [[UILabel alloc] init];
// special charactor
NSArray *suits = @[
[NSString stringWithUTF8String:“\xe2\x99\xa0\xef\xb8\x8f”],
[NSString stringWithUTF8String:“\xe2\x99\xa5\xef\xb8\x8f”],
[NSString stringWithUTF8String:“\xe2\x99\xa3\xef\xb8\x8f”],
[NSString stringWithUTF8String:“\xe2\x99\xa6\xef\xb8\x8f”]];
l.text = suits[v.tag – 1];
[l sizeToFit];
l.center = CGPointMake(CGRectGetMidX(v.bounds), CGRectGetMidY(v.bounds));
[v addSubview:l];
}
else if (v.subviews.count > 0)
{
[v.subviews[0] removeFromSuperview];
[v.layer addSublayer:[self cardBack]];
}
[UIView transitionWithView:v duration:0.5 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
} completion:^(BOOL finished) {}];
}
@end