Mopsaopsa Mopsaopsa - 2 months ago 12
Swift Question

Use slider to pick a color for view's background

I'm trying to write a function that should help me pick rainbow color from slider and set it on the view background.

Slider should have all rainbow colors presented, and as user slide it, view background changes according to it.

I did something like this, but it is showing only one color:

@IBOutlet var slider: UISlider!
@IBAction func changeColor(sender: AnyObject) {

var increment:CGFloat = 0.05
var counter = slider.value

for counter = 1; counter<=20; counter++ {
for var hue:CGFloat=0.0; hue < 1.0; hue+=increment {

var color = UIColor(hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
self.view.backgroundColor = color
}
}
}

Answer

It doesn't make sense to have a loop here. Your code is ignoring the slider value and always going through the loop, at the end setting the color to a hue of 1.0. (And it's doing this entire loop 20 times! So the inner code is actually running 400 times total, 20 x 20.)

You can just set the background color to a single color:

@IBOutlet var slider: UISlider!       

@IBAction func changeColor(sender: AnyObject) {
  var colorValue = CGFloat(slider.value)
  var color = UIColor(hue: colorValue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
  self.view.backgroundColor = color
}

This assumes you have left the slider's minimum value at 0 and maximum value at 1.0 in InterfaceBuilder.

Edit: Since slider.value goes from 0 to 1.0, it mirrors the allowed values for hue. We can just convert it to CGFloat and use it directly. Thanks @leo.

Comments