Skip to content

Instantly share code, notes, and snippets.

@zakbarlow1995
Last active September 16, 2021 23:01
Show Gist options
  • Save zakbarlow1995/eb399beedc38a699c961453b227b6d3e to your computer and use it in GitHub Desktop.
Save zakbarlow1995/eb399beedc38a699c961453b227b6d3e to your computer and use it in GitHub Desktop.
UIColor extension to add .random & .inverted static and computed variables, respectively.
import UIKit
// Extension adding class var random & computed property inverted to UIColor
extension UIColor {
static var random: UIColor {
UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: .random(in: 0...1))
}
static var randomSolid: UIColor {
UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
}
var inverted: UIColor {
var a: CGFloat = 0.0, r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0
return getRed(&r, green: &g, blue: &b, alpha: &a) ? UIColor(red: 1.0-r, green: 1.0-g, blue: 1.0-b, alpha: a) : .black
}
}
@zakbarlow1995
Copy link
Author

zakbarlow1995 commented Jul 19, 2019

Example usage, changing a view's background color:

view.backgroundColor = .blue.inverted //Results in yellow background color *
view.backgroundColor = .random //Results in random background color

* .blue.inverted may need to be prefixed with UIColor, depending on Xcode version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment