SwiftSwiftUISnippet
Last updated at 2023-07-26

How to Create Color.random in SwiftUI

ClickUp
Note
AI Status
Last Edit By
Last edited time
Jul 26, 2023 12:50 AM
Metatag
Slug
create-color-random-in-swiftui
Writer
Published
Published
Date
Jul 10, 2023
Category
Swift
SwiftUI
Snippet
You want to test the SwiftUI feature and debug how it works. That’s nice.
Because Color conforms to the View protocol, you can use that to show how your UI behaves.
For example, you want to check the SwiftUI LazyVGrid, ScrollView offset, VStack children space, and ZStack children position. All of those can be done using Color.
But you must need a random color because, without a random color, you cannot distinguish between views.
Or if you want color with a border, that can also be an option.
If you want to know how to debug a view using color, you need to add border to the view.
You can check how to create View with border here:
Rectangle() .frame(width: 200, height: 200) .border(Color.red, width: 2)

Create Random Color

Pseudo Random

In this code, you manually iterate the array one by one for each color when Color.random invoked. When the index reaches the end of the array, it automatically wraps using the remainder operator to avoid Array index out of bounds.
Read more about the remainder operator in Swift here.
extension Color { static var index = 0 static var random: Color { let colors = [ Color.red, .green, .blue, .orange, .yellow, .pink, .purple, .gray, .black, .primary, .secondary, .accentColor, .primary.opacity(0.5), .secondary.opacity(0.5), .accentColor.opacity(0.5) ] index += 1 return colors[index % colors.count] } }

Using Array Random Element

In this code, you use Array.randomElement() to let Swift select a color from colors variable.
extension Color { static var random: Color { let colors = [ Color.red, .green, .blue, .orange, .yellow, .pink, .purple, .gray, .black, .primary, .secondary, .accentColor, .primary.opacity(0.5), .secondary.opacity(0.5), .accentColor.opacity(0.5) ] return colors.randomElement()! } }
 

Discussion (0)

Related Posts