2011-05-01 46 views
0

我一直在为此工作数日,现在我的文本字段出现了一些嗡嗡的事情...而且它已经到了需要退后一步的地步,希望有一双新鲜眼睛的人可以揭示这种情况。UITextField在格式化NSString时出现NSString长度问题

基本上我正在做的是将20个字符的字符串格式化为5个字符串,因为用户在每个第5个字符之后输入一个连字符弹出到字符串中,这很好用。

我有一个提交按钮,在输入第20个字符之前是不可行的,这也适用,但是它在哪里变得很疯狂!如果你删除了一个字符的提交按钮仍然工作..然后你删除了一个字符,它不起作用...我不知道如果我的if语句条件不工作,我应该指定== 23个字符,你必须按下其中一个键24次才能进入该语句。这没有任何逻辑意义。

无论如何,如果你能帮助我的第一个问题,那将是伟大的,那么如果你对第二个问题有任何想法,那就太棒了。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    NSString *separator = @"-"; 
    int seperatorInterval = 5; //how many chars between each hyphen 
    NSString *originalString = [regTextField.text stringByReplacingOccurrencesOfString:separator withString:@""]; 


    if (textField.text.length == 23 && range.length == 0){ 
     return NO; // return NO to not change text 
    }  
    if (![originalString isEqualToString:@""] && ![string isEqualToString:@""]) { 

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

     if (![lastChar isEqualToString:separator] && modulus == 0) { 
       regTextField.text = [regTextField.text stringByAppendingString:separator]; 
     } 
    } 
    [self validateTextFields]; 
    return YES; //Keep accepting input from the user 
} 

//Validating text field to see if Submit button can be pressed or not 
-(IBAction) validateTextFields { 
    NSString *intString = [NSString stringWithFormat:@"%d", regTextField.text.length]; 
    NSLog(@"Starting %@", intString); 
    if (regTextField.text.length < 22){ 
     [submitButton setEnabled:NO]; //enables submitButton 
    } 
    else { 
     regTextField.text = [regTextField.text substringToIndex:22]; 
     [submitButton setEnabled:YES]; //disables submitButton 
    } 
    intString = [NSString stringWithFormat:@"%d", regTextField.text.length]; 
    NSLog(@"Done %@", intString); 
} 

回答

0

您需要的if语句

if (regTextField.text.length <= 22){ 

添加=登录本或者只是改变数到23无论哪种方式,它应该工作

if (regTextField.text.length < 23){