I am trying to create a slider such that at the initial load of the app, the slider has a default value, say 5. But if I were to change the slider value to 10, and leave the VC and come back, I would like the value to be 10. I have tried implementing this into my app but every time I return to the VC after leaving, the value is reset to the value I gave it in the StoryBoard. My code does circumnavigate this by making a value of 0 into 1 (which will always be the case for the first time the code runs), but I don't believe it is elegant, and there are better alternatives. I think I am not using viewDidAppear and viewDidLoad correctly, but I am not quite sure how to improve my code. Below is my attempt:
var distanceMap: Int = Int()
import UIKit
class MapSettingsVC: UIViewController {
//IBOutlet for the slider
@IBOutlet weak var rangeSlider: UISlider!
// label for slider value
@IBOutlet weak var distanceLabel: UILabel!
//changes to slider value
@IBAction func distanceRange(_ sender: UISlider) {
distanceMap = Int(sender.value)
distanceLabel.text = String(distanceMap)
}
// iboutlet to go to another viewController
@IBAction func backButtonTapped(_ sender: AnyObject) {
self.performSegue(withIdentifier: "mapSettingsGoBack", sender: self)
}
override func viewDidAppear(_ animated: Bool) {
rangeSlider.value = Float(distanceMap)
distanceLabel.text = String(Int(rangeSlider.value))
// I have initialized the label to be 0, so this will be FIRST value when the VC is loaded, and the if statement always runs the first time
if distanceLabel.text == "0" {
rangeSlider.value = 1
distanceLabel.text = "1"
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
Ideally I wouldn't want the slider to even have an option of '0', and to have the default set to 5.