ios - swift 2 : Call a method after pressing Return in UITextField

标签 ios swift uitextfield

我在小费计算器中有一个文本字段。我想让小费计算器更新我计算器的所有字段。

无论出于何种原因,使用我现在拥有的当前代码。它不会调用 calcTip()(或至少它似乎不会),直到我按一次回车键,输入另一个(或相同的)值并再次按回车键。

我真的很接近让这个应用程序完全按照我想要的方式工作,而且我觉得我只差 1 或 2 行。

我的 ViewController 符合 UITextFieldDelegate,我在 viewDidLoad 中声明了 amountBeforeTaxTextField.delegate = self。

文本应返回:

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

计算提示():

    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)
}

注意:使用和不使用 .becomeFirstResponder() 的结果相同

感谢阅读。

最佳答案

因此,当您按下键盘上的右下按钮时,您的 textFieldShouldReturn 函数将被调用,该按钮可以有各种标题;例如“开始”、“返回”、“完成”或“发送”。

你的第一行,只完成了一个UI效果;这意味着当用户点击文本字段输入文本时,文本字段的最右侧会出现一个小框,允许用户清除输入的文本(如果有)。有点像重置。

当您使用 becomeFirstResponder 时,您几乎是在调用另一个键盘弹出,因此您不会通过这样做完成任何事情。

当你使用 resignFirstResponder 时,你隐藏了键盘。

您要做的是删除“becomeFirstResponder”以及第一行,因为它们对解决您的问题没有任何帮助。这应该是您面临的问题的解决方案。

关于ios - swift 2 : Call a method after pressing Return in UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33792641/

相关文章:

iphone - 不会触发任何与方向相关的通知。为什么?

swift - 在 Swift 中从数组创建字典

swift - 在 UICollectionView 中点击按钮时字段 UITextField

uikit - 使自定义 SwiftUI View 适应内置修饰符

ios - 仅显示 Array 中的部分对象

像 iOS 6 一样的 iOS 7 状态栏

xcode - Xcode 4 中的设备选择被禁用,管理器中的绿灯

ios - 滚动背景在图像之间创建间隙 - Swift

ios - 如何获取 View 的框架并将其设置为渐变的框架

swift - 错误: Expression pattern of type 'CountableClosedRange<Int>' cannot match values of type 'UITextField!'