以前基本是使用一个按钮的两种状态,Normal/Disabled或者Normal/Selected,使用UIButton的下面两个方法设置不同状态下的文字颜色和图片
- (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setImage:(nullable UIImage *)image forState:(UIControlState)state;
今天有一个复选框需要用到两种状态的组合,Selected和Disabled,用上面的方式进行设置
[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];
运行后发现状态跟图标一直对不上,于是分析了一下按钮的状态,其实现在按钮已经有四种状态:
- 正常状态,enabled|unselected
- 选中状态,enabled|selected
- 禁用状态,disabled|unselected
- 选中状态下禁用,disabled|selected
我们设置了按钮的三种状态下的样式,Normal,Disabled,Selected, 显然只能满足前面三种状态,在第四中状态disabled|selected 时,UIButton就不知道要使用哪张图片了。
回到代码看下UIControlState
这个枚举
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
};
其实UIControlState是一个NS_OPTIONS,可以使用按位与操作符连接两个状态,所以修改代码如下:
[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];
这样设置后按钮的图片就跟预期的一致了。