之前写过一个关于按钮改变状态的片段,但是有点繁琐,最近get了一个简单的方法。
1.首先设置一个全局变量_startBtn,用来转换选中时的button
@interface OrderViewController ()<UITableViewDataSource, UITableViewDelegate>{
UIButton *_stateBtn;//
UIButton *_startBtn;
}
2.布局
#pragma mark -- 布局订单按钮的状态
-(void)LayoutOrderState {
UIView *stateView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, UIScreenWidth, 40)];
stateView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:stateView];
for (int i = 0; i < 4; i++) {
_stateBtn = [UIButton buttonWithType:UIButtonTypeSystem];
_stateBtn.frame = CGRectMake(0 + (UIScreenWidth - 3) / 4 * i, 64, (UIScreenWidth - 3) / 4, 40);
NSArray *stateArr = @[@"全部", @"待付款", @"配送中", @"待收货"];
[_stateBtn setTitle:stateArr[i] forState:UIControlStateNormal];
_stateBtn.titleLabel.font = [UIFont systemFontOfSize:14];
_stateBtn.tag = 100 + i;
//点击事件
[_stateBtn addTarget:self action:@selector(handleAction:) forControlEvents:UIControlEventTouchUpInside];
if (100 == _stateBtn.tag) {
[_stateBtn setTitleColor:[UIColor colorWithRed:250 / 255.0 green:60 / 255.0 blue:6 / 255.0 alpha:1] forState:UIControlStateNormal];
_startBtn = _stateBtn;//此时将第一个按钮赋给转换按钮
}else {
[_stateBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}
[self.view addSubview:_stateBtn];
}
}
3.点击事件
//状态按钮的点击事件
-(void)handleAction:(UIButton *)button {
[_startBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor colorWithRed:250 / 255.0 green:60 / 255.0 blue:6 / 255.0 alpha:1] forState:UIControlStateNormal ];
_startBtn = button;
}