下面给初学者学习一个简单的小游戏 --利用两张图片制作关灯游戏。游戏规则:点击其中一个按钮时,它本身及其周围的四个图都会变化。
新建一个myButton类继承于NSObject,
myButton.h
typedef NS_ENUM(NSInteger, Buttontype) {
ButtonUp,
ButtonDown
};
@interface myButton : UIButton
@property (assign, nonatomic) Buttontype type;
myButton.m
- (void)dealloc{
[super dealloc];
}
//初始化
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
新建一个myViewController 继承于UIViewController,调用myButton类
myViewController.m
- (void)dealloc{
[super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//绘制4x4的图形界面,并且为每个按钮添加动作,当点击按钮时,按钮本身及周围的按钮都会随之变化
NSInteger count = 100;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
//为每个按钮添加一个tag值,以便能够准确的找出点击按钮的上下左右按钮,
myButton *button = [[myButton alloc] initWithFrame:CGRectMake(20 + j * 85, 30 + i * 85, 80, 80)];
[button setImage:[UIImage imageNamed:@"1.jpg"] forState:UIControlStateNormal];
button.tag = count * (i + 1) + (j + 1);
button.type = ButtonUp;
[button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[button release];
}
}
}
- (void) action:(id)sender{
//确定点击按钮的上下左右按钮
myButton * button = (myButton *)sender;
myButton * buttonUp = (myButton *)[self.view viewWithTag:button.tag - 100];
myButton * buttonDown = (myButton *)[self.view viewWithTag:button.tag + 100];
myButton * buttonLeft = (myButton *)[self.view viewWithTag:button.tag - 1];
myButton * buttonRight = (myButton *)[self.view viewWithTag:button.tag + 1];
[self ButtonAction:button];
[self ButtonAction:buttonUp];
[self ButtonAction:buttonDown];
[self ButtonAction:buttonLeft];
[self ButtonAction:buttonRight];
}
- (void) ButtonAction:(myButton *)button{
if (button.type == ButtonUp) {
//首先要确定按钮是否实在点击状态,如果是出于点击状态,图片改变,状态改变
[button setImage:[UIImage imageNamed:@"2.jpg"] forState:UIControlStateNormal];
button.type = ButtonDown;
}else{
[button setImage:[UIImage imageNamed:@"1.jpg"] forState:UIControlStateNormal];
button.type = ButtonUp;
}
}
AppDelegate.m
- (void)dealloc{
[self.window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
_window.backgroundColor = [UIColor whiteColor];
[_window makeKeyAndVisible];
[_window release];
myViewController *myView = [[myViewController alloc] init];
[self.window setRootViewController:myView];
[myView release];
return YES;
}
*利用View的道理于与利用Button的道理一样,同上。