I have declared a variable tipPercentage
, a UISlider Action tipSliderAction
, and a UILabel tipPercentageLabel
.
I also created a clear
function, so that, when I tap a button, all the above are reset to default values.
Here is the code:
var tipPercentage = 1
@IBOutlet weak var tipPercentageLabel: UILabel!
@IBOutlet weak var tipSlider: UISlider!
@IBAction func tipSliderAction(sender: UISlider) {
let currentValue = Int(sender.value)
tipPercentageLabel.text = ("\(currentValue)")
let percentage = Double(currentValue) / 100
tipPercentage = percentage
}
@IBAction private func clear(sender: UIButton) {
tipSlider.value = 10
tipPercentageLabel.text = String(tipSlider.value)
tipPercentage = tipSlider.value
clear
function is where I reset the values to default. I guess my question is, instead of resetting each individual variables, is there a way to just reset one, then all others will update themselves?
For example, in the clear
function, when I just set the tipSlider.value
to 10, the tipPercentageLabel.text
and tipPercentage
will be updated without me setting them in the clear
function.
Thank you.
You can do this by adding a handler for ValueChanged event of your UISlider.
override func viewDidLoad()
{
super.viewDidLoad()
tipSlider.addTarget(self, action: #selector(ViewController.onValueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
}
@IBAction func onValueChanged(sender: AnyObject)
{
tipPercentageLabel.text = String(tipSlider.value)
tipPercentage = tipSlider.value
}