效果
首先需要知道纯颜色生成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)
就是如此简单!