UIButton 的简单运用

//简单制作一个关灯游戏关灯游戏

//点击某一个灯,它,包括它四周的灯一起变化,关了的亮,亮的关

//建一个分类,它继承与UIView

#import <UIKit/UIKit.h>

//声明一个方法

@interface UIView (Change)

-(void)change;

@end

//实现这个方法

#import "UIView+Change.h"

@implementation UIView (Change)

-(void)change

{

//红的变黑,黑的变红

    if (self.backgroundColor==[UIColor redColor]) {

        self.backgroundColor=[UIColor blackColor];

    }

    else

    {

        self.backgroundColor=[UIColor redColor];

    }

}

@end

#import <UIKit/UIKit.h>

#import "UIView+Change.h"

@interface ViewController : UIViewController

//定义一个按钮控件的属性

@property (strong,nonatomic) UIButton *button;

//声明一个判断的方法

 -(void)chose:(UIButton *)button;

@end

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

//循环产生按钮视图 j=5,代表横排五个,i=9 代表竖排9个

    for (int i=1; i<=9; i++)

    {

        for (int j=1; j<=5; j++)

        {

        //Button的初始化

            self.button = [UIButton buttonWithType:UIButtonTypeCustom];

            self.button=[[UIButton alloc]initWithFrame:CGRectMake(19*j+(j-1)*60, 19.6*i+(i-1)*60, 60, 60)];

         //将Button创建为圆角矩形  

            [self.button.layer setCornerRadius:10.0];

        //给Button上初始颜色为红色,当成灯亮

            self.button.backgroundColor=[UIColor redColor];

            //给创建的每一个Button按钮视图赋一个初始tag值

            self.button.tag=(i-1)*5+j;

                 self.button.selected=YES;

                 [self.view addSubview:self.button];

//当触发事件UIControlEventTouchDown发生时,调用方法chose:

            [self.button addTarget:self action:@selector(chose:) forControlEvents:UIControlEventTouchDown];

        }

    }

}

//判断方法

-(void)chose:(UIButton *)button

{

    self.button=button;

//将Button的tag值转化为int类型赋给num

    int num=(int)self.button.tag;

//第num个Button变色

    [[self.view viewWithTag:num] change];

//判断第num个Button周围有没有其他的Button,有调用change方法,变色

    if ((num-1)>0&&((num%5)!=1)) {

        [[self.view viewWithTag:(num-1)] change];

    }

    if ((num-5)>0) {

        [[self.view viewWithTag:(num-5)] change];

    }

    if ((num+1)<=45&&((num%5)!=0)) {

        [[self.view viewWithTag:(num+1)] change];

    }

    if ((num+5)<=45) {

        [[self.view viewWithTag:(num+5)] change];

    }

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

原文地址:https://www.cnblogs.com/Always-LuoHan/p/5263886.html