Which event is used to detect the UITextfield in null state

84 views Asked by At

i'm trying develop a textfield switching from 1 to another automatically, similarly i can switch the textfield backwards, but in null state i can't switch the cursor into the previous textfield , i tried with EditingChange Event but when the textfield in null state the Editng Change function is not fired.

The code is :

@IBAction func textFieldEditingChanged(_ sender: UITextField) {

    if(sender.text?.characters.count == 1) {
        switch sender {
        case otpField1:
            otpField2.becomeFirstResponder()
        case otpField2:
            otpField3.becomeFirstResponder()
        case otpField3:
            otpField4.becomeFirstResponder()
        case otpField4:
            otpField4.resignFirstResponder()
        default:
            break
        }
    }else {

    }

    if ((sender.text?.characters.count)! <= 0 || sender.text! == "" || sender.text?.isEmpty == true) {

        switch sender {
        case otpField4:
            otpField3.becomeFirstResponder()
        case otpField3:
            otpField2.becomeFirstResponder()
        case otpField2:
            otpField1.becomeFirstResponder()
        case otpField1:
            otpField1.resignFirstResponder()
        default:
            break

        }
    }

}
3

There are 3 answers

1
Arasuvel On

In order find UITextField empty you can use isEmpty of String.

So here it will be:

sender.text.isEmpty

How I will use is

guard let email = emailTextField.text, !email.isEmpty else {
         return
}

Hopes this solves your problem.

0
Tj3n On

Rather implement the textfield delegate shouldChangeCharactersInRange and check in there, probably need to check for nil and some more stuff but this is the idea:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let newLength = (textField.text?.characters.count)! - range.length + string.characters.count

    if (textField.text?.characters.count)! > 0 && newLength == 0 {

        textField.text = ""

        switch textField {
         ....
        }
    }
    return true
}
0
pradeepchauhan_pc On

You can find with condition like

if textField.isEmpty or textField.text == "" {
   // Do your stuff here when textField is empty
}
else {
  // Do your stuff when textField is not empty
}