The SO thread gives a lot of code, isn't it enough ?
For instance, this extension to set a color image.
Code Block | extension UIButton { |
| private func imageWithColor(color: UIColor) -> UIImage { |
| let rect = CGRectMake(0.0, 0.0, 1.0, 1.0) |
| UIGraphicsBeginImageContext(rect.size) |
| let context = UIGraphicsGetCurrentContext() |
|
| CGContextSetFillColorWithColor(context, color.CGColor) |
| CGContextFillRect(context, rect) |
|
| let image = UIGraphicsGetImageFromCurrentImageContext() |
| UIGraphicsEndImageContext() |
|
| return image |
| } |
|
| func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) { |
| self.setBackgroundImage(imageWithColor(color), forState: state) |
| } |
| } |
For isHilighted, declare a subclass of UIButton
Code Block | class MyButton: UIButton { |
| override open var isHighlighted: Bool { |
| didSet { |
| backgroundColor = isHighlighted ? UIColor.blue : UIColor.red |
| } |
| } |
| } |