我試圖驗證textField中的文本長度。這是我嘗試的驗證文本字段長度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *textLenght = [NSString stringWithFormat:@"%@", [textField text]];
if ([textLenght length] > 5)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message"
message:@"Too long"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
return NO;
}
return YES;
}
此代碼效果很好。當我輸入5個以上的字符時,會顯示警告框。問題是,當我嘗試刪除文本字段的最後一個字符時,警告框會再次顯示。
如何解決這個問題?
爲什麼要創建它? – Ariel 2012-03-08 16:03:20
@Ariel正如我在我的回答中所說的,因爲字符用戶輸入可能是退格,它會減少字符串的長度,並且檢查邏輯將是正確的。 – Eugene 2012-03-08 18:02:36