Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Anatoli-Petrosyants/f336aedec10d97f1b0fb82f707e39085 to your computer and use it in GitHub Desktop.
Save Anatoli-Petrosyants/f336aedec10d97f1b0fb82f707e39085 to your computer and use it in GitHub Desktop.
extension UIButton {
// https://stackoverflow.com/questions/14523348/how-to-change-the-background-color-of-a-uibutton-while-its-highlighted
private func image(withColor color: UIColor) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
self.setBackgroundImage(image(withColor: color), for: state)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment