我正在研究具有多個UITextField的應用程序。對於一個的UITextField,我已經設置其委託的自我和我打電話的委託方法:需要將UITextField的字符輸入限制爲iOS中的兩個字符
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
做特定任務。但是,我在其他UITextFields的屏幕上我想做一些完全不同的事情,在這種情況下,將輸入的字符數限制爲兩個。不幸的是,我在網上看到的唯一可行的方法是使用上述方法進行限制。如果我已經使用上述方法爲另一個UITextField執行完全不同的操作,那麼這仍然是可能的,如果是這樣,如何?
爲了記錄在案,這裏是我目前實施的委託方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([[string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]]
isEqualToString:@""])
return YES;
NSString *previousValue = [[[textField.text stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] stringByReplacingOccurrencesOfString:@"." withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@""];
string = [string stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
NSString *modifiedValue = [NSString stringWithFormat:@"%@%@", previousValue, string];
if ([modifiedValue length] == 1) {
modifiedValue = [NSString stringWithFormat:@"0.0%@", string];
}
else if ([modifiedValue length] == 2) {
modifiedValue = [NSString stringWithFormat:@"0.%@%@", previousValue, string];
}
else if ([modifiedValue length] > 2) {
modifiedValue = [NSString stringWithFormat:@"%@.%@",[modifiedValue substringToIndex: modifiedValue.length-2],[modifiedValue substringFromIndex:modifiedValue.length-2]];
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:modifiedValue];
modifiedValue = [formatter stringFromNumber:decimal];
textField.text = modifiedValue;
return NO;
}
非常感謝您的解決方案。你的答案是最完整的:-) – syedfa