先创建一对ViewController文件,用来编写开灯关灯的实现
LightViewController.h
LightViewController.m
在.h文件里定义两个属性,一个line:灯的行数,col:灯的列数
@property(assign, nonatomic)NSInteger line;
@property(assign, nonatomic)NSInteger col;
封装一个铺灯界面的方法
-(void)makeLightGame:(NSInteger)line col:(NSInteger)col{
_line = line;
_col = col;
NSInteger x = (self.view.frame.size.width - 10)/col;
for (NSInteger i = 0; i < _line; i++) {
for (NSInteger j = 0; j < _col; j++) {
UIButton *but = [[UIButton alloc] initWithFrame:CGRectMake(10 + x*j, 30 + x*i, x - 1 , x-1)];
but.backgroundColor = [UIColor colorWithRed:0.804 green:0.243 blue:0.643 alpha:1];
//每个灯都是一个Button,给每个Button添加了点击事件
[but addTarget:self action:@selector(but:) forControlEvents:UIControlEventTouchUpInside];
//设置每个button的tag值,避免出现列如:点击第二排第一个灯的时候,第一排最后一个灯也被关掉。每排假装多了一个灯(button)
but.tag = 1 + j + (_col+1)*i;
[self.view addSubview:but];
}
}
}
实现点击事件方法
方法说明:点击了一个灯(button)之后执行下面的点击事件,并把点击的那个button作为参数传了进来,根据tag值找到上下左右四个灯,并且根据当时各个灯的状态进行开关(changeColor方法:开的话就置成关,关就置成开)。
-(void)but:(UIButton *)but{
//被点击的灯
//下面的灯
UIButton *up = (UIButton *)[self.view viewWithTag:but.tag - _col - 1];
[self changeColor:up];
//上面的灯
UIButton *down = (UIButton *)[self.view viewWithTag:but.tag + _col + 1];
[self changeColor:down];
//左边的灯,由于button的tag值是从1开始的,要避免遇到tag=0的那个button(tag=0默认为当前父类View,无法改变)。判断如果被点击的是第一排第一个灯就不检测左边的灯(因为左边的灯不存在)
UIButton *left = (UIButton *)[self.view viewWithTag:but.tag - 1];
if (left.tag != 0) {
[self changeColor:left];
}
//右边的灯
UIButton *right = (UIButton *)[self.view viewWithTag:but.tag + 1];
[self changeColor:right];
}
检测灯的状态进行开关操作方法—changeColor
-(void)changeColor:(UIButton *)but{
//判断按钮but是否是被点击过,开始都为开灯,如果被点击过那么此时应该是关灯状态,如果被点击过,开灯。
if (but.isSelected) {
but.backgroundColor = [UIColor colorWithRed:0.804 green:0.243 blue:0.643 alpha:1];
}else{
but.backgroundColor = [UIColor blackColor];
}
//被点击设置成没被点击(开灯状态),没被点击设置成被点击(关灯状态)
but.selected = !but.selected;
}