Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hisoka0917/53e1fdbd3aad1801100754d0e96ddc91 to your computer and use it in GitHub Desktop.
Save hisoka0917/53e1fdbd3aad1801100754d0e96ddc91 to your computer and use it in GitHub Desktop.
UIButton setBackgroundColor for state in Swift 4
extension UIButton {
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
if let currentGraphicsContext = UIGraphicsGetCurrentContext() {
currentGraphicsContext.setFillColor(color.cgColor)
currentGraphicsContext.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
}
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: state)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment