for循环创建button控件

#import "ViewController.h"

#define Start_X          30.0f      // 第一个按钮的X坐标
#define Start_Y          200.0f     // 第一个按钮的Y坐标
#define Width_Space      5.0f      // 2个按钮之间的横间距
#define Height_Space     20.0f     // 竖间距
#define Button_Height   45.0f    // 高
#define Button_Width    100.0f    // 宽

@interface ViewController ()
@end

@implementation ViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  [self  addSubButtons];
}

-(void)addSubButtons
{
   //循环创建按钮
   for (int i = 0; i < 8; i ++) {
        NSInteger index = i % 3;
        NSInteger page = i / 3;
       
       // 圆角按钮
      UIButton *subBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
      subBtn.tag = i;//这句话不写等于废了
      subBtn.frame = CGRectMake(index * (Button_Width + Width_Space) + Start_X, page  * (Button_Height + Height_Space)+Start_Y, Button_Width, Button_Height);
      [self.view addSubview: subBtn];
       
       NSArray *titleArr = [NSArray arrayWithObjects:@"001",@"002",@"003",@"004",@"005",@"006",@"007",@"008", nil];
      subBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
      [subBtn setTitle:titleArr[i] forState:UIControlStateNormal];
      subBtn.backgroundColor = [UIColor orangeColor];
      [subBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
      //按钮点击方法
      [subBtn addTarget:self action:@selector(subBtnClick:) forControlEvents:UIControlEventTouchUpInside];
   }
}

//点击按钮方法,这里容易犯错
-(void) subBtnClick:(UIButton *)sender{
    //记住,这里不能写成"subBtn.tag",这样你点击任何一个button,都只能获取到最后一个button的值,因为前边的按钮都被最后一个button给覆盖了
     NSLog(@"%ld",sender.tag);
}

@end

你可能感兴趣的:(for循环创建button控件)