Random uicolor from string array
Here's an example of one way to do this:
import UIKit
extension Array {
func randomElement() -> Element {
return self[Int(arc4random_uniform(UInt32(self.count)))]
}
}
extension UIColor {
enum ColorEnum: String {
case red // = "red"
case green // = "green"
case blue // = "blue"
case pink // = "pink"
func toColor() -> UIColor {
switch self {
case .red:
return .redColor()
case .green:
return .greenColor()
case .blue:
return .blueColor()
case .pink:
return UIColor(hue: 1.0, saturation: 0.25, brightness: 1.0, alpha: 1.0)
}
}
}
static func fromString(name: String) -> UIColor? {
return ColorEnum(rawValue: name)?.toColor()
}
}
let colors = ["red", "green", "pink"] // stored as String
UIColor.fromString(colors.randomElement())
let enumColors: [UIColor.ColorEnum] = [.red, .green, .pink] // stored as enum
enumColors.randomElement().toColor()
Generate a random UIColor
Because you have assigned the colour values to int
variables. Use float
(or CGFloat
) instead. Also (as @stackunderflow's said), the remainder must
be taken modulo 256 in order to cover the whole range 0.0 ... 1.0
:
CGFloat red = arc4random() % 256 / 255.0;
// Or (recommended):
CGFloat red = arc4random_uniform(256) / 255.0;
Button that will generate a random background color - Xcode - Swift
As long as changeColor
is in your view controller, you can just do
@IBAction func changeColor(sender: UIButton) {
self.view.backgroundColor = UIColor.randomColor()
}
and then you have to connect a touch event of your button (say, touchUpInside) to the action. You can do that in Interface Builder (easy) or in code (trickier, but equally easy when you get the hang of it).
How to randomly color a UILabel
myLabel.backgroundColor = random([myBlue, myRed, myGreen, myYellow])
func random(colors: [UIColor]) -> UIColor {
return colors[Int(arc4random_uniform(colors.count))]
}
Swift: How can I change the background color randomly every second?
Try this code:
import UIKit
class ViewController: UIViewController {
var timer: NSTimer!
func setRandomBackgroundColor() {
let colors = [
UIColor(red: 233/255, green: 203/255, blue: 198/255, alpha: 1),
UIColor(red: 38/255, green: 188/255, blue: 192/255, alpha: 1),
UIColor(red: 253/255, green: 221/255, blue: 164/255, alpha: 1),
UIColor(red: 235/255, green: 154/255, blue: 171/255, alpha: 1),
UIColor(red: 87/255, green: 141/255, blue: 155/255, alpha: 1)
]
let randomColor = Int(arc4random_uniform(UInt32 (colors.count)))
self.view.backgroundColor = colors[randomColor]
}
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("setRandomBackgroundColor"), userInfo: nil, repeats: true)
self.setRandomBackgroundColor()
}
}
What I changed: I've renamed your randomColorGenerator
function into setRandomBackgroundColor
. Then I made this function to really change color instead of just calculating and returning some random index.
Some other minor changes: let randomColor = Int(arc4random_uniform(4))
you can use UInt32(colors.count)
instead of hardcoded constant 4
.
var timer = NSTimer()
– you don't need to initialize this timer, you are not using this initial value later. It's enough to just declare variable type: var time: NSTimer!
In your initial example, you were calculating random index each second, but you were not using it then to actually set the background color.
Related Topics
Real Time Nstask Output to Nstextview With Swift
How to Use Attributed String in Swiftui
Programmatically Detect Tab Bar or Tabview Height in Swiftui
== Overload for Custom Class Is Not Always Called
What Does the Dollar Sign Do in Swift/Swiftui
Lidar and Realitykit - Capture a Real World Texture For a Scanned Model
Having Hard Time Implement a Simple Singleton in Swift
Swift 4 Decodable - Dictionary With Enum as Key
How to Avoid Force Unwrapping a Variable
How to Set Cell Spacing and Uicollectionview - Uicollectionviewflowlayout Size Ratio
How to Stop a Dispatchworkitem in Gcd
What Does "@Uiapplicationmain" Mean
Cannot Assign Property in Method of Struct
Sheet Inside Foreach Doesn't Loop Over Items Swiftui