I want to create a UISlider that when a user selects a tableview row. It updates the min & max value moves the slider to a value set by a variable.
The slider is in a different Viewcontroller then the tableview. I am passing the values to the slider using a struct (Posted below). At this point, I can get the slider to work when I set the struct values in the view controller viewDidLoad. But I am not able to change the UIslider when a tableview row is selected. I think the problem is that the view with the UIslider is not refreshing when the row is selected. the Tableview is embedded in the view with the slider using a container view.
struct GlobalSliderValues {
static var minimumValue = Int()
static var maximumValue = Int()
static var lowerValue = Int()
static var UpperValue = Int()
static var locationValue = Int()
static var sliderValue = Int()
static var setValue = Int()
}
// Slider ViewController
override func viewDidLoad() {
super.viewDidLoad()
sliderOutlet.minimumValue = Float(GlobalSliderValues.minimumValue)
sliderOutlet.maximumValue = Float(GlobalSliderValues.maximumValue)
sliderOutlet.isContinuous = true
sliderOutlet.tintColor = UIColor.green
sliderOutlet.value = Float(GlobalSliderValues.sliderValue)
}
// Method attempting to change Slider
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 3:
GlobalSliderValues.minimumValue = 100
GlobalSliderValues.maximumValue = 10000000
GlobalSliderValues.sliderValue = 100000000
default:
break
}
}
try to refactor the slider assignment also adding NotificationCenter
to be able to refresh the slider from anywhere, doing so:
override func viewDidLoad() {
super.viewDidLoad()
sliderOutlet.isContinuous = true
sliderOutlet.tintColor = UIColor.green
self.refreshSlider()
}
@objc func refreshSlider() {
sliderOutlet.minimumValue = Float(GlobalSliderValues.minimumValue)
sliderOutlet.maximumValue = Float(GlobalSliderValues.maximumValue)
sliderOutlet.value = Float(GlobalSliderValues.sliderValue)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshSlider), name: Notification.Name("refreshSlider"), object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: Notification.Name("refreshSlider"), object: nil)
}
and finally inside your didSelectRowAt
you will have:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 3:
GlobalSliderValues.minimumValue = 100
GlobalSliderValues.maximumValue = 10000000
GlobalSliderValues.sliderValue = 100000000
NotificationCenter.default.post(name:Notification.Name("refreshSlider"), object: nil)
break:
default:
break
}
}