Pierre
Pierre

Reputation: 11633

delete last character UITextField

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

How can I do this?

Upvotes: 2

Views: 2889

Answers (3)

Akshaya
Akshaya

Reputation: 1

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

    if (textField.text.length > 8) {
        return  NO;
    }  
    return YES;

}

Upvotes: 0

glorifiedHacker
glorifiedHacker

Reputation: 6420

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...

Upvotes: 0

Vladimir
Vladimir

Reputation: 170829

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.

Upvotes: 2

Related Questions