Y Alsadah
Y Alsadah

Reputation: 1

Updating UILabel when one of 2 textfields are updated

Basically, I am trying to develop an app that has 3 labels, 2 editable & 1 which is not. The 2 editable texts are parameters in a formula, when one of them is updated, the uneditable label should automatically be updated (Think about this as y = a + b, if a is updated, y should automatically be updated).

My problem is that while I formulated a function for the y formula above, I can't seem to get y to update automatically. I have used UITextFieldDelegate's function textField as below:

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var weight: UITextField!
@IBOutlet weak var length: UITextField!
@IBOutlet weak var bmi: UILabel!
@IBOutlet weak var bmiCategory: UILabel!
@IBOutlet weak var textField1: UILabel!
@IBOutlet weak var textField2: UILabel!

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    bmi.text = String(bmiCalculator())
    return true
}

func bmiCalculator() -> Float {

    let weightValue: Float
    let lengthValue: Float
    let bmiValue: Float
    weightValue = (weight.text! as NSString).floatValue
    lengthValue = (length.text! as NSString).floatValue
    bmiValue = Float(formatFloat(value: weightValue / (lengthValue * lengthValue)))!
    print(bmiValue)
    return bmiValue

}

func formatFloat(value: Float) -> String {
    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 1
    let result = formatter.string(from: value as NSNumber)
    return result!
}

}

Note: The code will execute and the build will succeed, but the label will not be automatically updated.

Upvotes: 0

Views: 124

Answers (2)

Y Alsadah
Y Alsadah

Reputation: 1

Found the answer in a different way: I defined "a" & "b" as both IBOutlets and IBActions, where the IBAction would execute a function that will call the function bmiCalculator() upon an update in the textfield. see below:

@IBAction func weightFieldUpdate(_ textField: UITextField) {
    bmi.text = String(bmiCalculator())
}
@IBAction func lengthFieldUpdate(_ textField: UITextField) {
    bmi.text = String(bmiCalculator())
}

EDIT: I also found out that this functionality can be done with only 1 IBAction since the same code is executing

@IBAction func weightAndLengthUpdate(_ textField: UITextField) {
    bmi.text = String(bmiCalculator())
}

All thats required is to link the two UITextFields to this IBAction.

Upvotes: 0

Phillip Mills
Phillip Mills

Reputation: 31016

You're attempting the calculation too soon. You've been asked whether the field should change and you're calling a method to use existing values before you respond to allow it.

I suggest handling the UITextFieldTextDidChange notification and updating your dependent label there.

Upvotes: 1

Related Questions