Generate Random Colors in Swift

Posted by

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s