Reputation: 13
I'm trying to create a flashlight app for school and I wanted to add a slider to change the background from black to white. I can't seem to be able to figure it out.
I've tried some basic things, but nothing I've seen online works. It's either out of date or I'm just not understanding something.
Upvotes: 0
Views: 2928
Reputation: 56
So first you should get slidder value by creating an @IBAction for its value change and then using it to adjust the color of the background
override func viewDidLoad() {
slider.minimumValue = 0.0
slider.maximumValue = 255.0
}
@IBAction func sliderValueChanged(_ sender: UISlider) {
let currentValue = Int(sender.value)
let backgroundColor = UIColor(
red: CGFloat(currentValue),
green: CGFloat(currentValue),
blue: CGFloat(currentValue),
alpha:1.0
)
self.view.backgroundColor = backgroundColor
}
Upvotes: 1
Reputation: 180
Assuming you want to use a switch. You can make an if-else statement and change the color of the view based on if the switch is enabled or not. This would be an instant change, not a gradual change.
@IBAction func `switch`(_ sender: Any) {
if ((sender as AnyObject).isOn == true){
view.backgroundColor = UIColor.white
} else {
view.backgroundColor = UIColor.black
}
}
Upvotes: 0