How to make a random color with Swift

后端 未结 11 1536
甜味超标
甜味超标 2020-11-27 04:01

How I can make a random color function using Swift?

import UIKit

class ViewController: UIViewController {

    var randomNumber = arc4random_uniform(20)
            


        
11条回答
  •  离开以前
    2020-11-27 04:36

    For Swift 4.2

    extension UIColor {
        static var random: UIColor {
            return UIColor(red: .random(in: 0...1),
                           green: .random(in: 0...1),
                           blue: .random(in: 0...1),
                           alpha: 1.0)
        }
    }
    

    For Swift 3 and above:

    extension CGFloat {
        static var random: CGFloat {
            return CGFloat(arc4random()) / CGFloat(UInt32.max)
        }
    }
    
    extension UIColor {
        static var random: UIColor {
            return UIColor(red: .random, green: .random, blue: .random, alpha: 1.0)
        }
    }
    

    Usage:

    let myColor: UIColor = .random
    

提交回复
热议问题