Search code examples
iosswiftuser-interfaceuitextfielduislider

change Value in a TextField with Sliders based on a calculated Value [Swift]


I am creating some simple Input/Output stuffs. I have a function which calculates something and returns the value in a textfield. I want to change the value in the textfield with a slider based on this calculated value. Let's say my function returns the value 4,76 and my maximum value of the slider should be value*2 (= 9,52) and the minimum value is 0. My problem is I don't really know how I should create a slider which changes a value, where the value is not hardcoded.

@IBAction func slider(_ sender: UISlider) {
    sender.value = Float(calculateWaterAmount())!
    sender.minimumValue = 0
    sender.maximumValue = sender.value*2

    waterAmountTextField.text = String(sender.value)
}

The function calculateWaterAmount() returns a Double value. The slider should be able to change the value of this function and return it into a textField.

EDIT: so basically it should look like this slider with value. the value which will be displayed in the textfield depends on the formula in the function calculateWaterAmount() and each time i call the function with different values it should obviously return different values and the slider should may change the displayed value, if needed, to, lets say, a value between 0 and n*2, where n = calculated value


Solution

  • You need to call

    slider.maximumValue = Float(calculateWaterAmount()) * 2.0
    

    every time water amount changed. With this you'll always have maximumValue equals the doubled value of the func