Reputation: 68
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
}
}
}
Upvotes: 3
Views: 4949
Reputation: 236260
Try like this:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(hue: 0.5, saturation: 1, brightness: 1, alpha: 1)
}
@IBAction func colorChanged(_ slider: UISlider) {
view.backgroundColor = UIColor(hue: CGFloat(slider.value), saturation: 1, brightness: 1, alpha: 1)
}
}
Upvotes: 3
Reputation: 8652
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.
Upvotes: 3