ViewController.m 文件
- (void)viewDidLoad
{
[super viewDidLoad];
//循环绘制7行4列的view,并指定大小
for (int i=0; i<<span style="color: #0433ff">4; i++) {
for (int j=0; j<<span style="color: #0433ff">7; j++) {
LightView *lv=[[LightView alloc]initWithFrame:CGRectMake(20+70*i, 10+65*j, 48, 48)];
//表明每个view的tag值
lv.tag=100+10*i+j;
[self.view addSubview:lv];
}
}
}
记得创建子类LightView。
LightView.h 声明文件
#import
@interface LightView : UIView
@property (assign,nonatomic) BOOL flag;//标示图形的状态 true对应红旗,false对应绿旗。
@property (retain,nonatomic)UIGestureRecognizer *gr;
//宏定义
#define REDFLAG [UIColor colorWithPatternImage:[UIImage imageNamed:@"h"]]
#define GREENFLAG [UIColor colorWithPatternImage:[UIImage imageNamed:@"g"]]
@implementation LightView
@synthesize flag,gr;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//BOOL值的默认值为假,所以得指定它的默认值为真,且图像为g
//初始的时候指定背景图像
self.flag=true;
self.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"g"]];
//创建单击
self.gr=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
//添加手势
[self addGestureRecognizer:self.gr];
// Initialization code
}
return self;
}
//单击调用方法
-(void)tap:(UITapGestureRecognizer *)sender{
NSLog(@"单击");
//为什么要强转,不强转,类型不匹配。
LightView *lv1=(LightView *)[self.superview viewWithTag:self.tag-1];
LightView *lv2=(LightView *)[self.superview viewWithTag:self.tag+1];
LightView *lv3=(LightView *)[self.superview viewWithTag:self.tag-10];
LightView *lv4=(LightView *)[self.superview viewWithTag:self.tag+10];
[self changeLight];
[lv1 changeLight];
[lv2 changeLight];
[lv3 changeLight];
[lv4 changeLight];
}
//方法
-(void) changeLight{
//开始动画,beginAnimations:是动画名;context:是参数
[UIView beginAnimations:nil context:nil];
//动画执行1秒
[UIView setAnimationDuration:1];
//动画翻转,从右翻转
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self cache:YES];
//判断背景颜色为真的时候,图片是h,否则为假,为g;
//记住BOOL值的默认值为假
// if (self.flag==true) {
// self.backgroundColor=REDFLAG;
// self.flag=false;
// }else{
// self.backgroundColor=GREENFLAG;
// self.flag=true;
// }
//以下这两行相当于上面的if判断
//如果为真就是REDFLAG;如果为假就是GREENFLAG;
self.backgroundColor=self.flag?REDFLAG:GREENFLAG;
self.flag=!self.flag;
//执行动画
[UIView commitAnimations];
}
@end
当然,做关灯游戏需要素材,图片什么的自己定义。这几段代码使用手势和view结合写的。当然也可以用button来写,就是把所有的view定义成button。做的比较粗糙,见谅哈!