iOS限制文本框输入两位小数和最大值
- 实际开发中,经常会遇到这样的场景:限制某个文本框输入的最大值和小数位数,具体实现方式有很多,我这里用的是
正则+代理
的方式实现,思路如下:
设置文本框代理
self.txfAmount.delegate = self;
定义最大值的宏,方便以后修改
#define kMaxAmount 99999999
实现UITextFieldDelegate
#pragma mark - <UITextFieldDelegate>
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *amountText = self.txfAmount.text;
NSString *regStr = @"^([1-9][\\d]{0,100}|0)(\\.[\\d]{0,1})?$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regStr];
BOOL match = [predicate evaluateWithObject:amountText];
if ([string isEqualToString:@""]) return YES;
NSString *tmpStr = [amountText stringByAppendingString:string];
NSString *numStr = [[tmpStr componentsSeparatedByString:@"."] firstObject];
NSInteger amount = [numStr integerValue];
if (([amountText integerValue] == kMaxAmount) && (![string isEqualToString:@""])) return NO;
BOOL result = [amountText isEqualToString:@""] ? YES : (match && ((amount <= kMaxAmount) || [string isEqualToString:@"."]));
return result;
}