我正在开发一个具有多个 UITextField 的应用程序。对于一个 UITextField,我已将其委托(delegate)设置为 self 并调用委托(delegate)方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
执行特定任务。但是,我在同一屏幕上有其他 UITextFields,我想做一些完全不同的事情,在这种情况下,将输入的字符数限制为两个。不幸的是,我在网上看到的唯一可行的方法是使用上述方法来进行限制。如果我已经使用上述方法为另一个 UITextField 做一些完全不同的事情,这仍然可能吗?如果可以,怎么做?
郑重声明,这是我当前对委托(delegate)方法的实现:
- (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;
}
最佳答案
将两个文本字段用作类中的属性。例如,这是您的 Controller 的界面。
@interface YourViewController : UIViewContoller <UITextFieldDelegate> {
}
/*
* other properties
*/
@property(nonatomic, retain) UITextField *firstRestrictionTextField;
@property(nonatomic, retain) UITextField *yourSecondTextField;
@end
在您的实现中,两个文本字段都应设置为您的类的委托(delegate):
self.firstRestrictionTextField.delegate = self;
self.yourSecondTextField.delegate = self;
当你实现委托(delegate)方法时:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.firstRestrictionTextField) {
// Do stuff you need in first textfield
}
if (textField == self.yourSecondTextField) {
// Do stuff for your second textfield
}
}
关于ios - iOS中需要将UITextField的字符输入限制为两个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696446/