Skip to content

Instantly share code, notes, and snippets.

@mohitnandwani
Created March 15, 2022 18:07
Show Gist options
  • Save mohitnandwani/70870e0283ef90b73d6dea22b1ae319a to your computer and use it in GitHub Desktop.
Save mohitnandwani/70870e0283ef90b73d6dea22b1ae319a to your computer and use it in GitHub Desktop.
Generating random color in SwiftUI
// Based on this gist: https://gist.github.com/EnesKaraosman/efb9c2d989e51d20253976c8fb1aa734
// This particular gist is made to prefer iOS system colors over any random color
#if canImport(UIKit)
import UIKit
extension UIColor {
public static func random() -> UIColor {
let colors: [UIColor]
if #available(iOS 15.0, *) {
colors = [.systemBlue, .systemBrown, .systemCyan, .systemGray, .systemGreen, .systemIndigo, .systemMint, .systemOrange, .systemPink, .systemPurple, .systemTeal, .systemYellow, .systemRed]
} else {
colors = [.systemBlue, .systemBrown, .systemGray, .systemGreen, .systemIndigo, .systemOrange, .systemPink, .systemPurple, .systemTeal, .systemYellow, .systemRed]
}
return colors.randomElement() ?? UIColor(red: Double.random(in: 0...1), green: Double.random(in: 0...1), blue: Double.random(in: 0...1), alpha: 1)
}
}
#elseif canImport(SwiftUI)
import SwiftUI
extension Color {
public static func random() -> Color {
let colors: [Color]
if #available(iOS 15.0, *) {
colors = [Color(.systemBlue), Color(.systemBrown), Color(.systemCyan), Color(.systemGray), Color(.systemGreen), Color(.systemIndigo), Color(.systemMint), Color(.systemOrange), Color(.systemPink), Color(.systemPurple), Color(.systemTeal), Color(.systemYellow), Color(.systemRed)]
} else {
colors = [Color(.systemBlue), Color(.systemBrown), Color(.systemGray), Color(.systemGreen), Color(.systemIndigo), Color(.systemOrange), Color(.systemPink), Color(.systemPurple), Color(.systemTeal), Color(.systemYellow), Color(.systemRed)]
}
return colors.randomElement() ?? Color(red: Double.random(in: 0...1), green: Double.random(in: 0...1), blue: Double.random(in: 0...1))
}
}
#else
// all other platforms – use a custom color object
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment