Function for divide the value of a textfield?

Hey,

I want to divide the valune of a textfield and show it in a label, when I press a Button. Can someone send the code for this function?:)

Replies

You'll learn much more by writing the function yourself. Here are some hints to help :


I assume it is IOS App


1. You have an IBOutlet for the textField : myTextField, and for the label myLabel


2. Get the value of the textField

let valueString = myTextField.text // would be myTextField.stringValue for OSX


3. Convert to numeric value : what is the expected content ? Integer ? Float ? If it is Integer:

var value = Int(valueString) ?? 0 // 0 if not Int

// If it is a Float :

var value = Float(valueString) ?? 0.0


4. Divide by whatever divider you want ; test it is not 0

var newValue = 0.0 // Result will be

if divider != 0 {

newValue = Float(value) / Float(divider)

}


5. Set the new label

myLabel.text = String(newValue)


6. All this is inside the IBAction associated to the button

in step 4 it says: binary operator "/" cannot be applied to two "fload" operands!

How can I fix that ?

You should also declare : var newValue : Float = 0.0

So that compiler knows newValue is of type Float and not think it is Double

Thanks! 🙂