【篤行】Button的選中與改變

在項目中有時會遇到有幾個Button,當選中其中一個Button時,狀態顏色變爲選中狀態,其他的爲不選中狀態。
再次點擊選中狀態的Button狀態不改變(依舊是選中狀態)。

針對這種情況,需要創建使用一個全局的Button屬性。

@property(nonatomic,strong)UIButton *tempButton;

一般會有默認選中的Button,所以在默認的Button處寫上

    _liftButton.selected = YES;
    _tempButton = _liftButton;

將默認的Button賦給中間變量。

-具體示例代碼如下:

其實就是判斷點擊的Button是否爲選中狀態,是的話狀態不改變;不是的話,把記錄全局的Button選中狀態改爲NO,把當前的Button賦給全局Button,並且狀態改爲YES。

//按鈕點擊事件
-(void)buttonSelected:(UIButton *)sender{
    if (sender != _tempButton) {
        _tempButton.selected = NO;
        _tempButton.backgroundColor = [UIColor grayColor];
        sender.backgroundColor = [UIColor whiteColor];
        _tempButton = sender;
    }
    _tempButton.selected = YES;
}

​這裏用顏色來表示選中與未選中的狀態。

如果使用不同圖片,在創建Button時就可以設置選中與未選中的圖片,使用如下方法即可。
在點擊事件中就不需要在改變顏色了。

[button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:selectedImgName] forState:UIControlStateSelected];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章