-2

I want change color always when user tap on an element, but after tap I got white or transparent color (I don't see the object)

There is my code:

let red = arc4random_uniform(256)
let green = arc4random_uniform(256)
let blue = arc4random_uniform(256)
color = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(1))

If I use UIColor.green or another color its works

SmiLe
  • 311
  • 2
  • 13
  • 4
    I believe the arguments to `UIColor(red:, ...)` initializer should be in the range `[0.0, 1.0]`. – dfrib Mar 13 '17 at 16:36
  • 5
    Did you read the documentation for `UIColor`? That initialiser takes values between 0.0 and 1.0, not 0 - 255. – Grimxn Mar 13 '17 at 16:36
  • try http://stackoverflow.com/questions/29779128/how-to-make-a-random-background-color-with-swift – Ortensia C. Mar 13 '17 at 16:37
  • let red = arc4random_uniform(256) let green = arc4random_uniform(256) let blue = arc4random_uniform(256) let maxValue: Float = 255 let color = UIColor(red: CGFloat(Float(red)/maxValue), green: CGFloat(Float(green)/maxValue), blue: CGFloat(Float(blue)/maxValue), alpha: CGFloat(1)) – chinthakad Mar 13 '17 at 16:55

3 Answers3

2

RGB values have to be specified in the range of 0 to 1.0. Divide your RGB values by 256 since values above 1.0 are interpreted as 1.0. See https://developer.apple.com/reference/uikit/uicolor/1621925-init

0

Try dividing each of the values by 1 before creating a colour:

color = UIColor(red: CGFloat(1.0 / red), green: CGFloat(1.0 / green), blue: CGFloat(1.0 / blue), alpha: CGFloat(1))
Matthew Hallatt
  • 1,310
  • 12
  • 24
0

Try with this.

let red = randomInteger(limited: 256)
let green = randomInteger(limited: 256)
let blue = randomInteger(limited: 256)

color = UIColor(red: CGFloat(256 / red), green: CGFloat(256 / green), blue: CGFloat(256 / blue), alpha: CGFloat(1.0))

public func randomInteger(limited limit: Int) -> Int
{
    return Int(arc4random_uniform(UInt32(limit)))
}

But you have to do something with the returnes values. Color range is from 0.0 to 1.0

Adolfo
  • 1,862
  • 13
  • 19