9
votes

Comment détecter quand Uitextfield devient vide

Je voudrais effectuer une certaine action lorsque Uitextfield devient vide (l'utilisateur supprime tout un signe après l'autre ou utilise l'option Clear).

J'ai pensé à utiliser deux méthodes xxx

et xxx

de xxx

Je ne sais pas comment détecter la situation lorsque le champ de texte devient vide? J'ai essayé avec: xxx

mais il ne fonctionne pas car le FISRT des méthodes ci-dessus est appelé avant que le signe soit supprimé du champ de texte.

Toutes idées?


0 commentaires

4 Réponses :


38
votes
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSRange textFieldRange = NSMakeRange(0, [textField.text length]);
    if (NSEqualRanges(range, textFieldRange) && [string length] == 0) {
        // Game on: when you return YES from this, your field will be empty
    }
    return YES;
}
It's useful to note that the field won't be empty until after this method returns, so you might want to set some intermediate state here, then use textFieldDidEndEditing: to know that the user is done emptying out the field.

0 commentaires

0
votes

Le code suivant fonctionne aussi.

if (textField == first)
{

    [second becomeFirstResponder];

}
else if(textField == second)
{
    if (textField.text.length == 0)
    {
        [first becomeFirstResponder];
    }
    else
    {
        [third becomeFirstResponder];
    }

}
else if(textField == third)
{
    if (textField.text.length == 0)
    {
        [second becomeFirstResponder];
    }
    else
    {
         [four becomeFirstResponder];
    }

}

else if(textField == four)
{
    if (textField.text.length == 0)
    {
        [third becomeFirstResponder];
    }
    else
    {
        [four becomeFirstResponder];
    }

}
}


0 commentaires

5
votes

Si quiconque cherche la version Swift 4.2 de ce code est le suivant.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let textFieldRange = NSRange(location: 0, length: textField.text?.count ?? 0)
    if NSEqualRanges(range, textFieldRange) && string.count == 0 {
        // Do whatever you want when text field is empty.
    }
    return true
}


0 commentaires

0
votes

Voici une solution sans utiliser Nsrange

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if(textField.text.length==1 && string.length==0){
        //textfield is empty
    }else{
        //textfield is not empty
    }

    return true;
}


0 commentaires