2012-02-27 30 views
0

我一直在試圖通過互聯網上的許多可用代碼限制textField,但沒有運氣。xcode 4.2.1 - 在TextField中限制字符長度

我在頭文件在我viewDidLoad中

textField.delegate = self;加入UIViewController<UITextFieldDelegate>,在我的.m文件執行以下fundtion:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
    return !([newString length] > 5); 
} 

這還是老樣子不會限制我的文字領域。任何想法?

+1

[iPhone SDK:Set Max Character length TextField]可能的重複(http://stackoverflow.com/questions/433337/iphone-sdk-set-max-character-length-textfield) – Ilanchezhian 2012-02-27 07:19:36

+0

你做了什麼來嘗試調試它?您是否嘗試過記錄'[newString length]',例如? – dbrajkovic 2012-02-27 07:22:10

+0

我使用模擬器。並從一個定製鍵盤輸入字符 – Adeeb 2012-02-27 08:17:04

回答

2

就做如下,因爲它一直this

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    NSUInteger newLength = [textField.text length] + [string length] - range.length; 
    return (newLength > 5) ? NO : YES; 
} 
01的精確複製一個很好的效果都
+0

我做了,但仍然無法正常工作! – Adeeb 2012-02-27 07:39:04

0

替換字符串只是被按下的1個字符,而不是整個字符串,因此您需要在計數前將其添加到當前textfield.text中。 你計數可能是始終爲1(或更多,如果粘貼字)

+0

對不起,我不明白! – Adeeb 2012-02-27 07:39:57

+0

您的newstring只包含替換字符串,它只是輸入的新字符,因此它始終只有1個字符。你新增了將textfield.text添加到newstring以獲得完整的字符串。也許用stringwithformat:@「%@%@」,textfield.text,replacementstring];然後數它。 – Darren 2012-02-27 09:07:13

0

我在我的代碼來實現這一點,它的工作原理:

此代碼消除所有的字母只接受數字,但就像我刪除字符,你可以刪除它的長度超過5和它不斷出現和消失

- (void)textFieldDidBeginEditing:(UITextField *)textField { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextFieldTextDidChangeNotification object:textField]; 
} 


- (void)textChanged:(NSNotification *)textField { 
    NSString *text = [[textField object] text]; 
    NSString *last = [text substringFromIndex:[text length] -1]; 
    NSArray *accept = [NSArray arrayWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7" , @"8", @"9", @".", nil]; 

    for (int i=0; i<[accept count]; i++) { 
     NSLog(@"%@", [accept objectAtIndex:i]); 
     if (![last isEqualToString:[accept objectAtIndex:i]]) { 
      [[textField object] setText:[text substringToIndex:[text length]-1]]; 
     } 
    } 
} 
+0

此代碼沒有指定限制大小,並且在調試時出現錯誤:範圍或索引超出範圍 – Adeeb 2012-02-27 07:41:52

+0

突然檢查其長度超過5是否消除了最後一個字符 – Edig 2012-02-27 18:18:18