-1

So There are answers to this on SO but they are old and as far as I can tell in objectiveC, so...

I want to set the backgroundcolor using Int variables passed from a different view, like this:

backgroundView.backgroundColor = UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 0.5)

The variables red green blue used are like this:

var red: Int!
var green: Int!
var blue: Int!

With numbers from the previous view of course.

Xcode wants me to convert it to CGFloat like this:

backgroundView.backgroundColor = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 0.5)

But then the right color isn't carried over and only grey is shown.

I tried changing the Int variables to UIColor

var red: UIColor!

But that gave me an error...

So, how do I fix this?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
tore
  • 619
  • 2
  • 9
  • 23
  • 3
    What values are you storing in `red`, `green` and `blue`? – Rakesha Shastri Oct 02 '18 at 08:31
  • For view1: red = 144, green = 183, blue = 56, view2: red = 225, green = 163, blue = 38, view3: red = 186, green = 0, blue = 19, view4: red = 122, green = 28, blue = 125. Same result on all views... – tore Oct 02 '18 at 08:33
  • 1
    Type `let red = 144; print(red / 255)` into a Playground and you'll see the problem! (This is called “debugging” :) – Martin R Oct 02 '18 at 08:37
  • https://stackoverflow.com/questions/24263007/how-to-use-hex-colour-values – Sulthan Oct 02 '18 at 08:38

2 Answers2

1

You have to convert the value to float before dividing it by 255, otherwise it will make the division by two integers resulting always in 0:

CGFloat(red) / 255 = 0.5647058823529412
CGFloat(red / 255) = 0

backgroundView.backgroundColor = UIColor(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: 0.5)
LorenzOliveto
  • 7,796
  • 1
  • 20
  • 47
  • Yepp! There it is! Xcode autocorrected it to the one that didn't work. Now it works like a charm, thanks man! – tore Oct 02 '18 at 08:41
1

Try this

backgroundView.backgroundColor = UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 0.5)
Vladimir Kaltyrin
  • 621
  • 1
  • 4
  • 16