美文网首页
解决button被点击改变背景颜色的方法

解决button被点击改变背景颜色的方法

作者: EdwardSelf | 来源:发表于2016-07-26 14:48 被阅读1663次

    创建UIButton的分类

    .h文件:

    - (void)setBackgroundColor:(UIColor*)backgroundColor forState:(UIControlState)state;

    + (UIImage*)imageWithColor:(UIColor*)color;

    .m文件:

    - (void)setBackgroundColor:(UIColor*)backgroundColor forState:(UIControlState)state {

    [selfsetBackgroundImage:[UIButtonimageWithColor:backgroundColor]forState:state];

    }

    + (UIImage*)imageWithColor:(UIColor*)color {

    CGRectrect =CGRectMake(0.0f,0.0f,1.0f,1.0f);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRefcontext =UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [colorCGColor]);

    CGContextFillRect(context, rect);

    UIImage*image =UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    returnimage;

    }

    宏定义:

    #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]

    用法:

    [(UIButton *)sender setBackgroundColor:GetColorFromHex(0xD3D3D3) forState:UIControlStateNormal];

    [(UIButton *)sender setBackgroundColor:GetColorFromHex(0xF76063) forState:UIControlStateHighlighted];

    改变GetColorFromHex(),括号中的值,创建你想要的颜色,如果不知道,可以先滴出red,green,blue的数值,在storyboard的颜色设置里填上,会自动显示。

    相关文章

      网友评论

          本文标题:解决button被点击改变背景颜色的方法

          本文链接:https://www.haomeiwen.com/subject/lkbnjttx.html