2011-05-02 23 views
1

我目前正在格式化我的文本字段在xcode中,每添加一個連字符我都會添加一個字符。 但是我有很多麻煩,我目前想要檢查我的textfields.text.length,然後一旦長度達到23個字符的提交按鈕是可按下的。到目前爲止,這在我遇到困難的情況下是說,如果用戶輸入了23個字符,並且如果用戶決定返回並刪除一個字符,則按鈕是可按下的,因爲我不知道如何更新新文本的長度趕上號碼簿的刪除按鈕...劑量任何人都知道如何做到這一點?Numberpad退格不更新textField.text.length

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

嘗試是這樣的:

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