
行と列の数字からセルに色を付けるiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@interface ViewController () <UITextFieldDelegate>
@property (nonatomic, strong) NSMutableArray *titles;
@property (nonatomic, strong) NSMutableArray *cells;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
[self createAdditionTable];
}
– (void)createAdditionTable
{
self.titles = [NSMutableArray array];
self.cells = [NSMutableArray array];
// col, row title
for (int i=0; i<8; i++) {
float x = i * 30 + 60;
float y = 30;
UITextField *rt = [[UITextField alloc] initWithFrame:CGRectMake(x, y, 30, 30)];
rt.textAlignment = NSTextAlignmentCenter;
rt.text = @”1.0″;
rt.delegate = self;
[self.view addSubview:rt];
[self.titles addObject:rt];
}
for (int i=0; i<8; i++) {
float x = 30;
float y = i * 30 + 60;
UITextField *ct = [[UITextField alloc] initWithFrame:CGRectMake(x, y, 30, 30)];
ct.textAlignment = NSTextAlignmentCenter;
ct.text = @”1.0″;
ct.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
ct.delegate = self;
[self.view addSubview:ct];
[self.titles addObject:ct];
}
// cell
for (int i=0; i<64; i++) {
float x = (i % 8) * 30 + 60;
float y = (i / 8) * 30 + 60;
CALayer *cell = [CALayer layer];
cell.frame = CGRectMake(x, y, 30, 30);
cell.backgroundColor = [UIColor colorWithHue:1.0 saturation:0.8 brightness:1 alpha:1].CGColor;
[self.view.layer addSublayer:cell];
[self.cells addObject:cell];
}
// draw line
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(30, 30, 270, 270)];
for (int i=0; i<8; i++) {
[path moveToPoint:CGPointMake(i * 30 + 60, 30)];
[path addLineToPoint:CGPointMake(i * 30 + 60, 300)];
[path moveToPoint:CGPointMake(30, i * 30 + 60)];
[path addLineToPoint:CGPointMake(300, i * 30 + 60)];
}
CAShapeLayer *line = [CAShapeLayer layer];
line.fillColor = [UIColor clearColor].CGColor;
line.strokeColor = [UIColor lightGrayColor].CGColor;
line.path = path.CGPath;
[self.view.layer addSublayer:line];
}
– (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self updateColor];
return YES;
}
– (void)updateColor
{
for (int i=0; i<64; i++) {
CALayer *cell = self.cells[i];
float hue = ([[self.titles[i%8] text] floatValue] + [[self.titles[(i/8) + 8] text] floatValue]) / 2.0;
cell.backgroundColor = [UIColor colorWithHue:hue saturation:0.8 brightness:1 alpha:1].CGColor;
}
}
@end