我正在开发一个具有多个 UITextFields 的应用程序。对于一个 UITextField,我已将其委托设置为 self 并调用委托方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
完成一项特定的任务。但是,我在同一个屏幕上有其他 UITextField,我想做一些完全不同的事情,在这种情况下,将输入的字符数限制为两个。不幸的是,我在网上看到的唯一可能的方法是使用上述方法进行限制。如果我已经在使用上述方法为另一个 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;
}