[iOS]UITextFiled限制输入整数与小数位数
demo:http://download.csdn.net/download/u012881779/9958418
经常遇到用UITextFiled进行价格或折扣输入时,需要对输入进行限制,这里就根据逻辑写了下限制。
#pragma mark - UITextFieldDelegate - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSInteger theInteger = 100; NSInteger theDecimal = 100; if (textField.tag == 1000) { theInteger = 100; theDecimal = 3; } else if (textField.tag == 1001) { theInteger = 7; theDecimal = 2; } else if (textField.tag == 1002) { theInteger = 1; theDecimal = 1; } NSString *text = textField.text; NSInteger length = textField.text.length; if ([string isEqualToString:@""]) { return YES; } // 第一个字符不能输入“.” if (length == 0) { if ([string isEqualToString:@"."]) { return NO; } } else { if ([text containsString:@"."]) { if ([string isEqualToString:@"."]) { return NO; } // 限制小数位数 NSRange pointRange = [text rangeOfString:@"."]; if (length >= pointRange.location + pointRange.length + theDecimal) { return NO; } } else { if (length == 1) { // 第一个字符为“0”时,第二个字符必须为“.” if ([text isEqualToString:@"0"]) { if (![string isEqualToString:@"."]) { return NO; } } } if ([string isEqualToString:@"."]) { return YES; } // 限制整数位数 if (length >= theInteger) { return NO; } } } return YES; } 示意图: