// 创建按钮
NSArray * btnArray = @[@"工程师",@"学员"];
CGFloat w = (SCREEN_WIDTH-50)/2;
CGFloat h = 30;
CGFloat m = 20;
CGFloat x = 15;
for (int i = 0; i<btnArray.count; i++) {
NSInteger index = i % 2;
UIButton * buttonType = [[UIButton alloc] initWithFrame:CGRectMake(x+index*(w+m), 25, w, h)];
[buttonType setTitle:btnArray[i] forState:UIControlStateNormal];
[buttonType setTitleColor:mainBackColor forState:UIControlStateNormal];
[buttonType setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
buttonType.titleLabel.font = [UIFont fontWithName:@"PingFang SC" size: 15];
buttonType.tag = i+1;
[buttonType addTarget:self action:@selector(checkClick:) forControlEvents:UIControlEventTouchUpInside];
buttonType.layer.cornerRadius = 5;
buttonType.layer.borderWidth = 1;
buttonType.layer.borderColor = mainBackColor.CGColor;
if (i == 0) {
buttonType.selected = YES;
[buttonType setBackgroundColor:mainBackColor];
}else{
[buttonType setBackgroundColor:[UIColor whiteColor]];
}
[headView addSubview:buttonType];
}
// 按钮点击事件
-(void)checkClick:(UIButton *)sender{
//遍历数组 找出所有的button
for (int i = 0; i<2; i++) {
//获取button父视图上的所有子控件
UIButton * btn = (UIButton *)[self.view viewWithTag:i+1];
if (btn.tag != sender.tag) {
btn.selected = NO;
//未选中button的颜色
[btn setBackgroundColor:[UIColor whiteColor]];
}
}
sender.selected = YES;
//选中button的颜色
[sender setBackgroundColor:mainBackColor];
}