iOS小技巧

我们知道直接在Storyboard中设置按钮的背景色是不能根据不同状态来更改的,那问题来了,如果我们需要在不同的状态下(比如按钮没有被按下或者被按下),使得按钮呈现不同的背景色怎么办?

sample

比如上图左边是按钮没有被按下时的背景色,右边是按钮被按下时的背景色。

第一种方案

我们知道按钮的Image属性可以在不同的状态下设置不同的图片,那最直观的办法就是提供两种背景色的图片,然后直接在Storyboard上通过设置不同状态下Image属性的值来达到目的。

但是这种方案最不好的地方就在于需要提供很多仅仅是颜色不同的图片,如果以后背景色改成其他色系怎么办?设置以后提供换肤功能,每一种皮肤都要提供一整套这些背景色图片吗?

第二种方案

我们还知道按钮的BackgroundImage也是可以根据不同状态来设置不同的背景图片的,那方案就来了,让程序根据颜色自动生成不同的纯色背景图片即可。

为了保证可复用性,定义一个UIButton的Category,实现如下:

@implementation UIButton (FillColor)

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
	[self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];
}

+ (UIImage *)imageWithColor:(UIColor *)color {
	CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
	UIGraphicsBeginImageContext(rect.size);
	CGContextRef context = UIGraphicsGetCurrentContext();

	CGContextSetFillColorWithColor(context, [color CGColor]);
	CGContextFillRect(context, rect);

	UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();

	return image;
}

@end

上述代码应该还是很直观的,调用的办法如下:

[self.button setBackgroundColor:GetColorFromHex(0xffff9000) forState:UIControlStateNormal];
[self.button setBackgroundColor:GetColorFromHex(0xffff6c00) forState:UIControlStateHighlighted];

其中GetColorFromHex是我自己定义的一个宏:

#define GetColorFromHex(hexColor) 
[UIColor colorWithRed:((hexColor >> 16) & 0xFF) / 255.0 
		green:((hexColor >>  8) & 0xFF) / 255.0 
		 blue:((hexColor >>  0) & 0xFF) / 255.0 
		alpha:((hexColor >> 24) & 0xFF) / 255.0]

其实上述宏代码写成Category会更好,以后再做修改了。

当然根据一向的惯例,都会给出以上方法的出处(仍然是来自于码农的圣地StackOverflow):请点击这里

原文地址:https://www.cnblogs.com/shanpow/p/4162514.html