在AppDelegate.m文件中添加視圖控制器
#import "AppDelegate.h"
#import "RootViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
RootViewController *rootVC = [[RootViewController alloc]init];
self.window.rootViewController = rootVC;
[self.window makeKeyAndVisible];
return YES;
}
在RootViewController.m中實現 RootViewController 繼承於UIViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 300)];
[self.view addSubview:view];
CGFloat x,y;
x=0,y=0;
for (int i=0; i<5; i++) {
x=0; //每次初始化x
for (int j=0; j<5; j++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(x, y, 50, 50);//
button.backgroundColor = [UIColor grayColor];
button.layer.contentsScale=4;
button.layer.cornerRadius=14;
[button addTarget:self action:@selector(createbutton:) forControlEvents:UIControlEventTouchUpInside];
button.tag = 10*(i+1)+j+1; //行每次+1,列+10
//NSLog(@"%ld",(long)button.tag);
[view addSubview:button];
x+=50;
}
y+=50;
}
}
- (void)createbutton:(UIButton *)selectedButton
{
// NSLog(@"%ld",(long)selectedButton.tag);
//顏色調換
if (selectedButton.backgroundColor==[UIColor grayColor]) {
selectedButton.backgroundColor = [UIColor yellowColor];
} else{
selectedButton.backgroundColor = [UIColor grayColor];
}
//點擊的button上下左右取反
UIButton *up=(UIButton*)[[self.view superview]viewWithTag:selectedButton.tag-10];
if (up.backgroundColor==[UIColor grayColor]) {
up.backgroundColor = [UIColor yellowColor];
} else{
up.backgroundColor = [UIColor grayColor];
}
UIButton *down=(UIButton*)[[self.view superview]viewWithTag:selectedButton.tag+10];
if (down.backgroundColor==[UIColor grayColor]) {
down.backgroundColor = [UIColor yellowColor];
} else{
down.backgroundColor = [UIColor grayColor];
}
UIButton *left=(UIButton*)[[self.view superview]viewWithTag:selectedButton.tag-1];
if (left.backgroundColor==[UIColor grayColor]) {
left.backgroundColor = [UIColor yellowColor];
} else{
left.backgroundColor = [UIColor grayColor];
}
UIButton *right=(UIButton*)[[self.view superview]viewWithTag:selectedButton.tag+1];
if (right.backgroundColor==[UIColor grayColor]) {
right.backgroundColor = [UIColor yellowColor];
} else{
right.backgroundColor = [UIColor grayColor];
}
IOS簡單關燈小遊戲
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.