I have 2 x UITextfields for the user to put values in. I want to use those values as the Min & Max values for the UISlider Bar. I have been struggling with this for 2days already. Sorry, I am very new to coding.
This is my current code:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var sensorMinText: UITextField!
@IBOutlet weak var sensorMaxText: UITextField!
@IBOutlet weak var sliderLabel: UILabel!
var sensorMin: String?
var sensorMax: String?
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
Slider.value = 0
Slider.minimumValue =
Slider.maximumValue =
sliderLabel.text = String(Int(Slider.value))
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
@IBAction func sMinInput(_ sender: Any) {
sensorMin = sensorMinText.text
}
@IBAction func sMaxInput(_ sender: Any) {
sensorMax = sensorMaxText.text
}
@IBOutlet weak var Slider: UISlider!
@IBAction func sliderChanged(_ sender: UISlider) {
sliderLabel.text = String(Int(sender.value))
}
}
2
Answers
You don’t say what platform you are working on, although your code references
UIKit
, so I am assuming this is for iOS. You should add an iOS tag to your question.You don’t have any code that attempts to set the max and min of your slider.
Have you tried to tackle that part yet?
You need to have numeric properties (not strings) for your slider max and slider min values. When the user enters a new min or max value, you need to validate the input, and then update the numeric max/min value.
You could add a didSet on your max and min inputs that would apply the new limit to your
UISlider
.If you look in the docs for
UISlider
it says:Accessing the slider’s value limits
var minimumValue: Float
The minimum value of the slider.
var maximumValue: Float
The maximum value of the slider.
Those are the slider properties you would need to modify.
That’s a good application possibility for the Combine framework.
First things first
Then add an extension of
UITextField
to get notified ontextDidChange
In the view controller on the top level create a property to hold the subscriptions
and in
viewDidLoad
implement the subscriptions which update the min and max properties of the slider when the text changes respectively.Important: The keyboard type of both text fields must be Decimal Pad and assign default min and max values to both the text fields and the slider (by the way name the
slider
IBOutlet lowercase)