// -------协议方法--------
-(BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string{
//小数点只能一个
if([string isEqualToString:@"."] && ([textField.text rangeOfString:@"."].location!=NSNotFound|| [textField.text isEqualToString:@""])) {
return NO;
}
//退格
if([string isEqualToString:@""]) {
return YES;
}
// 首位输入0之后 只能输.或者退格
if([textField.text isEqualToString:@"0"] && ![string isEqualToString:@"."]) {
return NO;
}
//小数点后面长度不超过2位
BOOL isHasDot = false;// 是否包含小数点
if([textField.text rangeOfString:@"."].location != NSNotFound) {
isHasDot = true;
}
if(isHasDot) {
//小数点位置
NSRange dotRange = [textField.text rangeOfString:@"."];
if(range.location - dotRange.location>2) {
[self showHint:@"仅允许输入到小数点后两位"];
return NO;
}
}
//只能输入数字
if([string rangeOfString:@"."].location==NSNotFound) {
NSRange range = [string rangeOfString:@"^[0-9]+$"options:NSRegularExpressionSearch];
if(range.location==NSNotFound) {
return NO;
}
}
return YES;
}
网友评论