【问题标题】:UITextField Changes Not Being Detected?未检测到 UITextField 更改?
【发布时间】:2015-01-15 03:08:14
【问题描述】:

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

我是 swift 新手,所以请清楚你的答案。另外,我没有设置任何断点。这是我目前所拥有的代码:

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

【问题讨论】:

    标签: variables swift int uitextfield boolean


    【解决方案1】:

    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 控件事件并调用您注册的操作方法。

    【讨论】:

    • 谢谢!一个问题,我是新手,所以在我迄今为止编写的代码中添加这两行代码的合适位置是什么!谢谢!
    • 我在答案中概述了这一点。您很可能应该在 viewDidLoad() 中执行此操作。
    • 好的。谢谢!如果我有问题,我会告诉你。
    • 非常感谢!这有帮助!
    • 再问一个问题:如果我想在值发生变化时执行此操作(我会将控制事件更改为什么而不是 .EditingDidEnd)?
    猜你喜欢
    • 2012-12-06
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2015-07-20
    • 2015-06-19
    相关资源
    最近更新 更多