首页 > 代码库 > IOS 根据数组的个数对UIButton进行重复或循环使用

IOS 根据数组的个数对UIButton进行重复或循环使用

//设置一个view 

view = [[UIView alloc] initWithFrame:CGRectMake(0, 38, 320, 30)]; 

view.backgroundColor = [UIColor lightGrayColor]; 

[self.view addSubview:view]; 

 

for (int i=0; i<5; i++) { 

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 

button.tag = 100+i; 

button.frame = CGRectMake(64*i+3, 3, 58, 25); 

[button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchUpInside]; 

[button setTitle:[NSString stringWithFormat:@"%@",[array objectAtIndex:i]] forState:UIControlStateNormal]; 

//默认在第一个 

if (button.tag == 100) { 

[button setBackgroundImage:[UIImage imageNamed:@"blueBtn.png"] forState:UIControlStateNormal]; 

//将循环创建的button都添加到view上面 

[view addSubview:button]; 

#pragma mark - button触发的方法 

-(void)doButton:(UIButton *)sender 

for (UIButton *button in view.subviews) { 

if (button.tag != sender.tag) { 

[button setBackgroundImage:nil forState:UIControlStateNormal]; 

else 

[button setBackgroundImage:[UIImage imageNamed:@"blueBtn.png"] forState:UIControlStateNormal]; 

}