按钮的单选

// 创建按钮
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];

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容