方法一:用自定义button类做继承于UIButton
- (void)createView
{
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
MyButton *button = [[MyButton alloc] init];
button.frame = CGRectMake(j * 60 +50, i * 60 + 100, 50, 50);
[button setBackgroundImage:[UIImage imageNamed:@"b4.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(button1Action:) forControlEvents:UIControlEventTouchUpInside];
button.tag = 100 * (i + 1) + (j + 1);
[self.view addSubview:button];
[button release];
}
}
方法二:用自定义手势类做,继承于UIImageView
- (void)createView
{
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
MyimageView *image = [[MyimageView alloc]initWithFrame:CGRectMake(60 * j +50, i *60 + 100, 50, 50)];
image.tag = 100 * (i + 1) + (j + 1);
[image setImage:[UIImage imageNamed:@"b2.png"]];
image.userInteractionEnabled = YES;
[self.view addSubview:image];
[image release];
// 创建点击手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(imageAction:)];
// 给imageview,所以把它设置属性在.m中写
[image addGestureRecognizer:tap];
[tap release];
}
}
}
具体实现如下如果是用UIImageView跟这个类似:
- (void)button1Action:(id)sender{//sender:mybutton
MyButton *button = (MyButton *)sender;
NSInteger upTag = button.tag - 100;
NSInteger leftTag = button.tag + 1;
NSInteger rightTag = button.tag - 1;
NSInteger downTag = button.tag +100;
MyButton *upButton = (MyButton *)[self.view viewWithTag:upTag];
MyButton *leftButton = (MyButton *)[self.view viewWithTag:leftTag];
MyButton *rightButton = (MyButton *)[self.view viewWithTag:rightTag];
MyButton *downButton = (MyButton *)[self.view viewWithTag:downTag];
[self changeImage:button];
[self changeImage:upButton];
[self changeImage:downButton];
[self changeImage:leftButton];
[self changeImage:rightButton];
}
// 如果有两个代码是一样的只有对象不同,就设置形参
- (void)changeImage:(MyButton *)button
{
NSLog(@"%ld",button.ButtonState);
if (button.ButtonState ) {
[button setImage:[UIImage imageNamed:@"b4.png"] forState:UIControlStateNormal];
button.ButtonState = ButtonStateUp;
}else{
[button setImage:[UIImage imageNamed:@"b2.png"] forState:UIControlStateNormal];
button.ButtonState = ButtonStateDown;
}
}
注意:不论哪个方法,我都用了枚举
typedef NS_ENUM(NSInteger, ButtonState) {
ButtonStateUp ,
ButtonStateDown
};
@interface MyButton : UIButton
//@property (nonatomic ,assign) BOOL judge;
@property(nonatomic,assign)NSInteger ButtonState;
@end