IOS 给UIButton设置纯颜色带点击效果的背景

效果


首先需要知道纯颜色生成UIImage的方法

func imageWithColor(color:UIColor,size:CGSize) ->UIImage{

    let rect =CGRect(x:0, y:0, width: size.width, height: size.height)

    UIGraphicsBeginImageContext(rect.size)

    let context =UIGraphicsGetCurrentContext()

    CGContextSetFillColorWithColor(context, color.CGColor)

    CGContextFillRect(context, rect)

    let image =UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return image

}

然后设置UIButton 就OK了

let button =UIButton(frame:CGRect(x:100, y:100, width:100, height:100))

button.setBackgroundImage(imageWithColor(UIColor.whiteColor(), size: button.frame.size), forState: .Highlighted)

button.setBackgroundImage(imageWithColor(UIColor.redColor(), size: button.frame.size), forState: .Normal)

button.setTitle("哈哈", forState: .Normal)

button.titleLabel?.font=UIFont.systemFontOfSize(15)

button.setTitleColor(UIColor.redColor(), forState: .Highlighted)

button.setTitleColor(UIColor.whiteColor(), forState: .Normal)

view.addSubview(button)

就是如此简单!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容