UIButton无法正确显示高亮背景图标,显示效果偏灰色
最近遇到一个奇怪的问题。把一个的黑色图片设置成UIButton的高亮背景图像后,UIButton确显示成把它显示成灰色的。经过一番调教,仍不得其解。后来被同事指点,才找出问题根源。现在记下来,以防忘记。
1、问题
//生成一张黑色图片,设置成按钮背景 UIImage *backgroundImage = [UIImage imageWithPureColor:[UIColor blackColor]]; [self.xibButton setBackgroundImage:backgroundImage forState:UIControlStateHighlighted];
神奇之处就在于,最后显示效果如下:
2、调试
尝试手工创建一个button,然后设置背景色
//手工创建一个按钮 UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(200, 28, 80, 80)]; [button setTitle:@"code按钮" forState:UIControlStateNormal]; [button setTitleColor:[UIColor colorWithRed:61.0/255 green:90.0/255 blue:249.0/255 alpha:1] forState:UIControlStateNormal]; [self.view addSubview:button];
效果如下:
3、原因
UIButton有个属性 @property(nonatomic,readonly) UIButtonType buttonType;用来指示按钮样式。xib创建的默认样式为UIButtonTypeSystem,代码创建的样式为UIButtonTypeCustom。正式这个区别使得两种按钮的效果不同
4、验证
创建四个按钮。代码、xib与system、custom两两组合,效果如下:
代码如下:
- (void)viewDidLoad { [super viewDidLoad]; UIImage *backgroundImage = [UIImage imageWithPureColor:[UIColor blackColor]]; //创建第二个按钮 UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(200, 28, 80, 80)]; [button setTitle:@"code按钮" forState:UIControlStateNormal]; [button setTitleColor:[UIColor colorWithRed:61.0/255 green:90.0/255 blue:249.0/255 alpha:1] forState:UIControlStateNormal]; button.highlighted = YES; //方便演示 [self.view addSubview:button]; self.codeButton = button; //创建第四个按钮 button = [UIButton buttonWithType:UIButtonTypeSystem]; button.frame = CGRectMake(40, 240, 240, 80); [button setTitle:@"code按钮 type=system" forState:UIControlStateNormal]; [button setTitleColor:[UIColor colorWithRed:61.0/255 green:90.0/255 blue:249.0/255 alpha:1] forState:UIControlStateNormal]; button.highlighted = YES; //方便演示 [self.view addSubview:button]; self.codeSystemButton = button; [self.xibButton setBackgroundImage:backgroundImage forState:UIControlStateHighlighted]; [self.codeButton setBackgroundImage:backgroundImage forState:UIControlStateHighlighted]; [self.xibCustomButton setBackgroundImage:backgroundImage forState:UIControlStateHighlighted]; [self.codeSystemButton setBackgroundImage:backgroundImage forState:UIControlStateHighlighted]; }