发现问题
最近写项目中发现一个有趣儿的问题,UIButton 设置了 btn.enabled = NO;
但是 btn
显示的图片并非 UIControlStateDisabled
状态设置的图片。
问题出在哪里呢?请看下文分析。
UIButton的状态
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
};
最常用的是前四种(UIControlStateNormal、UIControlStateHighlighted、UIControlStateDisabled、UIControlStateSelected)。
思考
No bb, Show code
[btn setImage:[UIImage imageNamed:@"img0"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"img1"] forState:UIControlStateHighlighted];
[btn setImage:[UIImage imageNamed:@"img2"] forState:UIControlStateDisabled];
[btn setImage:[UIImage imageNamed:@"img2"] forState:UIControlStateSelected];
问题:如果如下设置,btn
会显示那张图片。
1.
btn.highlighted = YES;
btn.enabled = YES;
btn.selected = NO;// 显示 Highlighted
2.
btn.highlighted = YES;
btn.enabled = NO;
btn.selected = YES;// 显示 Normal
3.
btn.highlighted = NO;
btn.enabled = YES;
btn.selected = YES;// 显示 Selected
4.
btn.highlighted = NO;
btn.enabled = NO;
btn.selected = YES;// 显示 Normal
总结
当 btn
的两种状态展示设置有冲突(不分设置的先后顺序)时,系统会默认显示 UIControlStateNormal
状态的图片。无冲突时,正常显示。