1,首先新建视图控制器
2,在视图控制器中铺上5*5的小格,每个格都是一个新View,全部添加到视频控制器上
3,当点击时调用系统触摸方法,可以把实现关灯的方法写在触摸方法里
代码如下:
先铺格
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor blackColor];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(35 + j * 50, 40 + i * 50, 50, 50)];
[self.view addSubview:view1];
view1.layer.borderWidth = 0.5;
view1.backgroundColor = [UIColor whiteColor];
view1.tag += 10000 + j + i * 100;
[view1 release];
}
}
}
触摸
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
int array[] = {0, 1, -1, 100, -100};
int count = sizeof(array) / sizeof(array[0]);
for (int i = 0; i < count; i++) {
UIView *view = (UIView *)[self.view viewWithTag:(touch.view.tag + array[i])];
if ([view.backgroundColor isEqual:[UIColor whiteColor]]) {
view.backgroundColor = [UIColor clearColor];
} else if ([view.backgroundColor isEqual:[UIColor clearColor]]) {
view.backgroundColor = [UIColor whiteColor];
}
}
}
关灯游戏之图片换图片:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor blackColor];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(35 + j * 50, 40 + i * 50, 50, 50)];
imageView.userInteractionEnabled = YES;
[self.view addSubview:imageView];
UIImage *image = [UIImage imageNamed:@"1.jpg"];
imageView.image = image;
imageView.layer.borderWidth = 0.5;
imageView.tag += 10000 + j + i * 100;
[imageView release];
}
}
}
// 触摸
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
int array[] = {0, 1, -1, 100, -100};
int count = sizeof(array) / sizeof(array[0]);
UIImage *image1 = [UIImage imageNamed:@"1.jpg"];
UIImage *image2 = [UIImage imageNamed:@"2.jpg"];
for (int i = 0; i < count; i++) {
UIImageView *view = (UIImageView *)[self.view viewWithTag:(touch.view.tag + array[i])];
if ([view isKindOfClass:[UIImageView class]]) {
if ([view.image isEqual:image1]) {
view.image = image2;
} else {
view.image = image1;
}
}
}
}