开发者

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开发者_StackOverflow社区 log.

How can I do this?


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.


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


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

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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜