How do I check when a UITextField changes?

后端 未结 19 3215
情话喂你
情话喂你 2020-11-22 15:44

I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this:

  fu         


        
19条回答
  •  臣服心动
    2020-11-22 16:20

    In case it is not possible to bind the addTarget to your UITextField, I advise you to bind one of them as suggested above, and insert the code for execution at the end of the shouldChangeCharactersIn method.

    nameTextField.addTarget(self, action: #selector(RegistrationViewController.textFieldDidChange(_:)), for: .editingChanged)
    
    @objc func textFieldDidChange(_ textField: UITextField) {
        if phoneNumberTextField.text!.count == 17 && nameTextField.text!.count > 0 {
            continueButtonOutlet.backgroundColor = UIColor(.green)
        } else {
            continueButtonOutlet.backgroundColor = .systemGray
        }
    }
    

    And in call in shouldChangeCharactersIn func.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        guard let text = textField.text else {
            return true
        }
        let lastText = (text as NSString).replacingCharacters(in: range, with: string) as String
    
        if phoneNumberTextField == textField {
            textField.text = lastText.format("+7(NNN)-NNN-NN-NN", oldString: text)
            textFieldDidChange(phoneNumberTextField)
            return false
        }
        return true
    }
    

提交回复
热议问题