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)
        return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0)



view.backgroundColor = UIColor.random


Here is the github repo for the sample project:


Leave a Reply

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

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

Facebook photo

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

Connecting to %s