Numberpad退格键不更新textField.text.length

时间:2011-05-02 01:52:02

标签: iphone uitextfield numpad

我正在格式化xcode中的文本字段,每隔5个字符我添加一个连字符。 但是我有很多麻烦我目前想要检查我的textfields.text.length然后一旦长度达到23个字符,提交按钮是可按下的。到目前为止这个工作在我遇到麻烦的地方说如果用户输入23个字符并且按钮是可按下的,如果用户决定返回并删除一个字符则没有更新新文本长度,因为我不知道如何抓住数字键盘的删除按钮...任何人都知道怎么做?

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

    NSString *separator = @"-";
    int seperatorInterval = 5;
    NSString *originalString = [regTextField.text stringByReplacingOccurrencesOfString:separator withString:@""];



    if (![originalString isEqualToString:@""] && ![string isEqualToString:@""]) {

        NSString *lastChar = [regTextField.text substringFromIndex:[regTextField.text length] - 1];
        int modulus = [originalString length] % seperatorInterval;
        [self validateTextFields];

        if (![lastChar isEqualToString:separator] && modulus == 0) {

            regTextField.text = [regTextField.text stringByAppendingString:separator];
        }
    }
    [self validateTextFields];
    return YES;
}

    -(IBAction) validateTextFields {

    if (regTextField.text.length >= 22){
        [submitButton setEnabled:YES]; //enables submitButton
    } 
    else {
        [submitButton setEnabled:NO]; //disables submitButton

    }

}

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // Any new character added is passed in as the "text" parameter
    if (!([text isEqualToString:@""] && range.length == 1) && [textView.text length] >=140 ) {
        return NO;
    }
    // For any other character return TRUE so that the text gets added to the view
    return YES;
}

块:

([text isEqualToString:@""] && range.length == 1) 

是否检查退格。

Capturing the backspace on the Number Pad Keyboard