シンプルなそろばんのiPhoneアプリを書いてみます。タップでそろばんの玉が上下します。
動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@property (strong, nonatomic) UILabel *label;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
[self createSoroban];
[self createLabel];
}
– (void)createSoroban
{
int col = 4;
for (int i=0; i<col*5; i++) {
float x = (i/5) * 50 + 230;
float y = (i%5) * 40 + 120;
if (i%5 == 0) {
y -= 50;
}
UIView *tama = [self sorobanNoTama];
tama.center = CGPointMake(x, y);
tama.tag = col * 5 – i;
[self.view addSubview:tama];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[tama addGestureRecognizer:tap];
}
}
– (void)createLabel
{
self.label = [[UILabel alloc] initWithFrame:CGRectMake(40, 40, 100, 60)];
self.label.backgroundColor = [UIColor whiteColor];
self.label.layer.cornerRadius = 10;
self.label.font = [UIFont systemFontOfSize:30];
self.label.text = @”0″;
self.label.textColor = [UIColor lightGrayColor];
self.label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:self.label];
}
– (void)tap:(UITapGestureRecognizer*)gr
{
// reverse
if (!CGAffineTransformIsIdentity(gr.view.transform)) {
if (gr.view.tag % 5 == 0) {
gr.view.transform = CGAffineTransformIdentity;
}
else {
int n = gr.view.tag % 5;
for (int i=gr.view.tag; i>gr.view.tag – n; i–) {
UIView *t = [self.view viewWithTag:i];
t.transform = CGAffineTransformIdentity;
}
}
}
else {
if (gr.view.tag % 5 == 0) {
gr.view.transform = CGAffineTransformMakeTranslation(0, 20);
}
else {
int n = 5 – (gr.view.tag % 5);
for (int i=gr.view.tag; i<gr.view.tag + n; i++) {
UIView *t = [self.view viewWithTag:i];
t.transform = CGAffineTransformMakeTranslation(0, –20);
}
}
}
[self updateNumer];
}
– (void)updateNumer
{
int number = 0;
for (int i=1; i<=20; i++) {
UIView *t = [self.view viewWithTag:i];
if (CGAffineTransformIsIdentity(t.transform)) {
continue;
}
int n = i / 5;
if ((i % 5) == 0) {
number += 5 * pow(10, n – 1);
}
else
{
number += pow(10, n);
}
}
self.label.text = [NSString stringWithFormat:@”%d”, number];
}
– (UIView*)sorobanNoTama
{
float s = 40;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(s/2.0, 0)];
[path addLineToPoint:CGPointMake(s, s/2.0)];
[path addLineToPoint:CGPointMake(s/2.0, s)];
[path addLineToPoint:CGPointMake(0, s/2.0)];
[path closePath];
CAShapeLayer *sl = [CAShapeLayer layer];
sl.fillColor = [UIColor brownColor].CGColor;
sl.path = path.CGPath;
UIView *tama = [[UIView alloc] initWithFrame:CGRectMake(0, 0, s, s)];
[tama.layer addSublayer:sl];
[self.view addSubview:tama];
return tama;
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end