點擊按鈕改變顏色和狀態之二

之前寫過一個關於按鈕改變狀態的片段,但是有點繁瑣,最近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;

}





發佈了23 篇原創文章 · 獲贊 6 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章