Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a random color with Swift

How I can make a random color function using Swift?

import UIKit  class ViewController: UIViewController {      var randomNumber = arc4random_uniform(20)     var randomColor = arc4random()      //Color Background randomly     func colorBackground() {          // TODO: set a random color         view.backgroundColor = UIColor.yellow      } } 
like image 490
Giovanie Rodz Avatar asked Apr 21 '15 17:04

Giovanie Rodz


People also ask

How do you add a custom color in Swift?

There are two ways to use your custom colors in Swift UI. Select your object in device preview. Choose “Color” under the attributes inspector. Your custom colors now show at the bottom of the list!

How do I change colors in Swift?

Find the view or view controller you want to change the background color of. Open it up in the interface builder and open the Attributes Inspector. Find the background color field and set it to the color you want.


1 Answers

You're going to need a function to produce random CGFloats in the range 0 to 1:

extension CGFloat {     static func random() -> CGFloat {         return CGFloat(arc4random()) / CGFloat(UInt32.max)     } } 

Then you can use this to create a random colour:

extension UIColor {     static func random() -> UIColor {         return UIColor(            red:   .random(),            green: .random(),            blue:  .random(),            alpha: 1.0         )     } } 

If you wanted a random alpha, just create another random number for that too.

You can now assign your view's background colour like so:

self.view.backgroundColor = .random() 
like image 168
ABakerSmith Avatar answered Sep 24 '22 19:09

ABakerSmith