views:

212

answers:

2

Hi !

I have an UITextField and I just would like that every tap on a character, the first character is deleted. So just have one character in my textField every time. Moreover I would to to display every tap in the console log.

Have you got an idea?

Thanks!

+1  A: 

You need to implement shouldChangeCharactersInRange method in your text field delegate:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:
                  (NSRange)range replacementString:(NSString *)string{
    textField.text = @"";
    return YES;
}

You may need to check for range and string values to cover all possible cases (like copy/paste actions). This code just sets the text field's value to the last typed character.

Vladimir
Thanks a lot. Working great !
Pierre
A: 

UITextField inherits from UIControl, so you can use the target-action mechanism that is part of the UIControl class:

[textField addTarget:self action:@selector(updateTextField) forControlEvents:UIControlEventValueChanged];

In the action method, you can replace the UITextField's text with only the last character and log that character in the console. Note that since changing the UITextField's text will again result in the "updateTextField" message being sent a second time to the target, you will need some kind of mechanism for determining whether to update or not:

- (void)updateTextField {
    if(updateTextField == YES) {
        updateTextField = NO;
        NSString *lastChar = [textField.text substringFromIndex:[textField.text length]];
        [textField setText:lastChar];
        NSLog(@"%@", lastChar);
    } else {
        updateTextField = YES;
    }
}

Or something like that anyway...

glorifiedHacker