简体   繁体   中英

Swift 2: Call a method after pressing Return in UITextField

I have a Text Field in a Tip Calculator. I want the Tip Calculator to update all the fields of my calculator.

With the current code that I have now, for whatever reason. It doesn't call calcTip() (or atleast it doesn't seem to) until I press return once, enter another (or the same) value and press return again.

I'm really close to having this app work exactly how I want it to, and I feel like I'm just 1 or 2 lines away.

My ViewController conforms to UITextFieldDelegate, and I declared amountBeforeTaxTextField.delegate = self in viewDidLoad.

TextShouldReturn:

func textFieldShouldReturn(textField: UITextField) -> Bool {
        amountBeforeTaxTextField.clearsOnBeginEditing = true
        amountBeforeTaxTextField.becomeFirstResponder()
        calcTip()
        amountBeforeTaxTextField.resignFirstResponder()
    return true
}

calcTip():

    func calcTip() {
    let tip = tipCalc.calculateTip()
    let total = tipCalc.calculateTotal()
    let tax = tipCalc.calculateTax()
    let perPerson = total / Float(Int(partySizeSlider.value))

    tipCalc.tipPercentage = (tipPercentageSlider.value)
    tipCalc.amountBeforeTax = (amountBeforeTaxTextField.text! as
        NSString).floatValue
    tipCalc.taxPercentage = (taxPercentageSlider.value)
    resultLabel.text = String(format: "Tip $%.2f, Tax: $%.2f Total: $%.2f", tip, tax, total)
    perPersonLabel.text = String(format: "Per-Person Total: $%.2f", perPerson)
}

Note: I have the same outcome with & without .becomeFirstResponder()

Thanks for reading.

So your textFieldShouldReturn function is called when you press the bottom right button on the keyboard, which can have various titles; such as "Go", "Return", "Done", or "Send".

Your first line, only accomplishes a UI effect; meaning when the user taps on the textfield to input text, there will be a little box that appears on the far right handside of the textfield that allows the user to clear the inputted text, if there is any. Sort of like a reset.

When you use becomeFirstResponder, you are pretty much calling another keyboard to pop up, so you aren't accomplishing anything by doing that.

When you use resignFirstResponder, you are hiding the keyboard.

What you want to do is remove "becomeFirstResponder" as well as the first line, because those don't do anything to help your problem. That should be the solution to the problem you are facing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM