OC开发资料收集区

iOS button样式自定义

2017-07-24  本文已影响144人  oc123

本文分享作者在iOS开发过程中,遇到的关于button自定制样式的一些经验;
一、button自定义背景色
首先定义一个UIButton的category分类或者重写一个UIButton的子类,实现代码如下:

//state即button的状态
- (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;
}

本文将持续更新,如有帮助请关注!
荆轲刺秦王!

上一篇下一篇

猜你喜欢

热点阅读