We have all come across scenarios where we need to use random colors. For example, showing UIViewControllers with random background color in a UIPageViewController, or just show UITableViewCells with random background colors in a UITableView.
I have created an extension on UIColor to help me in the applications.
Here is the code in Swift 3:
extension UIColor {
static var random: UIColor {
// Seed (only once)
srand48(Int(arc4random()))
return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0)
}
}
Usage:
view.backgroundColor = UIColor.random
Here is the github repo for the sample project:
https://github.com/hashaam/Sample-RandomColor
Leave a comment