以前基本是使用一個(gè)按鈕的兩種狀態(tài),Normal/Disabled或者Normal/Selected宋舷,使用UIButton的下面兩個(gè)方法設(shè)置不同狀態(tài)下的文字顏色和圖片
- (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setImage:(nullable UIImage *)image forState:(UIControlState)state;
今天有一個(gè)復(fù)選框需要用到兩種狀態(tài)的組合,Selected和Disabled瓢姻,用上面的方式進(jìn)行設(shè)置
[self setImage:[UIImage imageNamed:@"round_uncheck"] forState:UIControlStateNormal];
[self setImage:[UIImage imageNamed:@"round_check"] forState:UIControlStateSelected];
[self setImage:[UIImage imageNamed:@"round_check_disabled"] forState:UIControlStateSelected];
運(yùn)行后發(fā)現(xiàn)狀態(tài)跟圖標(biāo)一直對(duì)不上祝蝠,于是分析了一下按鈕的狀態(tài),其實(shí)現(xiàn)在按鈕已經(jīng)有四種狀態(tài):
- 正常狀態(tài)幻碱,enabled|unselected
- 選中狀態(tài)绎狭,enabled|selected
- 禁用狀態(tài),disabled|unselected
- 選中狀態(tài)下禁用褥傍,disabled|selected
我們?cè)O(shè)置了按鈕的三種狀態(tài)下的樣式儡嘶,Normal,Disabled,Selected, 顯然只能滿足前面三種狀態(tài),在第四中狀態(tài)disabled|selected 時(shí)恍风,UIButton就不知道要使用哪張圖片了蹦狂。
回到代碼看下UIControlState
這個(gè)枚舉
typedef NS_OPTIONS(NSUInteger, UIControlState) {
UIControlStateNormal = 0,
UIControlStateHighlighted = 1 << 0, // used when UIControl isHighlighted is set
UIControlStateDisabled = 1 << 1,
UIControlStateSelected = 1 << 2, // flag usable by app (see below)
UIControlStateFocused NS_ENUM_AVAILABLE_IOS(9_0) = 1 << 3, // Applicable only when the screen supports focus
UIControlStateApplication = 0x00FF0000, // additional flags available for application use
UIControlStateReserved = 0xFF000000 // flags reserved for internal framework use
};
其實(shí)UIControlState是一個(gè)NS_OPTIONS,可以使用按位與操作符連接兩個(gè)狀態(tài)朋贬,所以修改代碼如下:
[self setImage:[UIImage imageNamed:@"round_uncheck"] forState:UIControlStateNormal|UIControlStateDisabled];
[self setImage:[UIImage imageNamed:@"round_check"] forState:UIControlStateSelected];
[self setImage:[UIImage imageNamed:@"round_check_disabled"] forState:UIControlStateSelected|UIControlStateDisabled];
這樣設(shè)置后按鈕的圖片就跟預(yù)期的一致了凯楔。