未检测到UITextField更改?

时间:2014-11-18 02:38:02

标签: variables swift int uitextfield boolean

我有两个标志属性,当文本字段包含整数时应该更改,并且当文本字段编辑结束时,我有IBActions更改标志。当两个变量都为真时,这些方法应该启用一个按钮。我运行了iOS模拟器,但按钮没有启用。我还为文本字段声明了文本字段委托。

我是新手,所以请明确你的回答。另外,我没有设置任何断点。这是我到目前为止的代码:

var yourWeightFilled = false
var calorieNumberFilled = false

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // Find out what the text field will be after adding the current edit
    let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

    if textField == yourWeightTextField {
        yourWeightFilled = text.toInt() != nil
    } else if textField == calorieNumberTextField {
        calorieNumberFilled = text.toInt() != nil
    }

    return true
}

@IBAction func yourWeightEditingDidEnd(sender: AnyObject) {
    if self.yourWeightFilled && self.calorieNumberFilled {
        self.calculateButton.enabled = true
    }
    yourWeightTextField.resignFirstResponder()
}

@IBAction func calorieNumberEditingDidEnd(sender: AnyObject) {
    if self.yourWeightFilled && self.calorieNumberFilled {
        self.calculateButton.enabled = true
    }
    calorieNumberTextField.resignFirstResponder()
}

1 个答案:

答案 0 :(得分:3)

UITextFieldUIControl的子类,因此需要调用action methods registered来响应控件事件。您可以使用addTarget(_:action:forControlEvents:)方法执行此操作。

例如:

weightField.addTarget(self, action:"yourWeightEditingDidEnd:", forControlEvents:.EditingDidEnd);

当用户完成编辑文本字段时,您的情况可以调用您的操作方法yourWeightEditingDidEnd()。这假设您的字段属性名为weightField。此代码的一个好地方在于视图控制器的viewDidLoad()方法。

还有一个重要的步骤。您似乎正在实现UITextFieldDelegate,这很好,因为您还需要一个返回true和resigns the text field as first respondertextFieldShouldReturn(textField:) -> Bool方法。例如:

func textFieldShouldReturn(textField: UITextField) -> Bool
{
    textField.resignFirstResponder();
    return true;
}

这反过来会导致.EditingDidEnd控件事件触发,并调用您注册的操作方法。

相关问题