Pergunta

Problem: I have a method that handles editingChanged events and another method that updates my textfields from an object model. The problem is that if I modify the text of the field that sent the event, it triggers editingChanged again and I enter an infinite loop (only in ios 5)!

Example:

- (IBAction)updateFields:(UITextField *)sender {
    if ([self myCustomValidation:sender]) {
        ... //update model
        //call another method that essentially does this
        field1.text = @"someformatted text"; //causes infinite loop if any field == sender
        field2.text = @"some more text";
    }
}

How do you work around this issue (without having to pass sender to all methods that send setText: messages) ?

Foi útil?

Solução

Consider implementing the UITextFieldDelegate's method textField:shouldChangeCharactersInRange:replacementString: instead of registering for the editingChanged control event.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    ... //update model
    //call another method that essentially does this
    field1.text = @"someformatted text";  //causes infinite loop any field == sender
    field2.text = @"some more text";
    return YES; // or NO, depending on you actions
}

According to the documentation it should serve your purposes

The text field calls this method whenever the user types a new character in the text field or deletes an existing character.

Outras dicas

Instead of writing your own IBAction methods, just implement UITexFeild delegates.

To detect modifying text, implement shouldChangeCharactersInRange delegate.

To detect end editing , implement textFieldDidEndEditing delegate.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range      replacementString:(NSString *)string
{
  //write ur code here
  return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top