运用button写的一个关灯游戏
声明了一个属性NSMutableArray *arr;
_arr = [[NSMutableArray
alloc]
init];
创建10行8列的button矩阵
for (
int i =
0; i <
10; i++) {
for (
int j =
0; j <
8; j++) {
UIButton *button = [UIButtonbuttonWithType
:UIButtonTypeSystem
];
button.
frame =
CGRectMake(
27.5 + j *
40,
20 + i *
40,
35,
35);
给button添加背景图片
[button setBackgroundImage
:[UIImageimageNamed
:@"12"]forState
:UIControlStateNormal
];
将button添加至数组
[
_arraddObject:button];
[
self.
viewaddSubview:button];
给button一个点击事件
[button addTarget
:selfaction
:@selector(buttonDidPress:)forControlEvents
:UIControlEventTouchUpInside
];
}
}
做了一个重新开始的button按钮
PS:后面的水印是失误,请忽略 - -
UIButton *button1 = [UIButtonbuttonWithType
:UIButtonTypeSystem
];
button1.
frame =
CGRectMake(
0,
500,
self.
view.
frame.
size.
width,
50);
button1.
backgroundColor = [
UIColorcyanColor];
[button1 setTitle
:@"重新开始"forState
:UIControlStateNormal
];
[button1 addTarget
:selfaction
:@selector(buttonNewGame:)forControlEvents
:UIControlEventTouchUpInside
];
[
self.
viewaddSubview:button1];
重新开始的点击事件
-(
void)buttonNewGame:(
UIButton *)sender {
for (
UIButton *button
in
_arr) {
[button setBackgroundImage
:[UIImageimageNamed
:@"12"]forState
:UIControlStateNormal
];
}
}
判断改变背景图片的点击事件
-(
void)buttonDidPress:(
UIButton *)sender {
这里的打印是找bug时用的
// NSLog(@"A");
遍历数组里的所有button
for (
UIButton *button
in
_arr) {
判断条件,找出与sender相邻的button
if (
fabs(button.
frame.
origin.
x
- sender.
frame.
origin.
x) +
fabs(button.
frame.
origin.
y - sender.
frame.
origin.
y)
==
40) {
// NSLog(@"B");
改变上面找出的button背景图片
if ([[button backgroundImageForState
:UIControlStateNormal
]isEqual
:[UIImageimageNamed
:@"12"]])
{
// NSLog(@"C");
[button setBackgroundImage
:[UIImageimageNamed
:@"23"]forState
:UIControlStateNormal
];
}
else {
[button setBackgroundImage
:[UIImageimageNamed
:@"12"]forState
:UIControlStateNormal
];
}
}
}
改变sender背景图片
if ([[senderbackgroundImageForState
:UIControlStateNormal
]isEqual
:[UIImageimageNamed
:@"23"]])
{
[(UIButton *)sendersetBackgroundImage
:[UIImageimageNamed
:@"12"]forState
:UIControlStateNormal
];
}
else {
[(UIButton *)sendersetBackgroundImage
:[UIImageimageNamed
:@"23"]forState
:UIControlStateNormal
];
}
}