#pragma mark - textFieldDelegate
//长度判断
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
if(textField ==self.accountField) {
NSScanner *scanner = [NSScannerscannerWithString:string];
NSCharacterSet*numbers;
NSRange pointRange = [textField.textrangeOfString:@"."];
if((pointRange.length>0) && (pointRange.location< range.location || pointRange.location> range.location+ range.length)) {
numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
}else{
numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
}
if([textField.textisEqualToString:@""] && [stringisEqualToString:@"."] ) {
returnNO;
}
shortremain =2;//默认保留2位小数
NSString*tempStr = [textField.textstringByAppendingString:string]; // 原来的字符+当前输入的字符
NSUIntegerstrlen = [tempStrlength];
if(pointRange.length>0&& pointRange.location>0) {//判断输入框内是否含有“.”。
if([string isEqualToString:@"."]) { //当输入框内已经含有“.”时,如果再输入“.”则被视为无效。
returnNO;
}
if(strlen >0&& (strlen - pointRange.location) > remain+1) {//当输入框内已经含有“.”,当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数,则视当次输入无效。
returnNO;
}
}
NSRangezeroRange = [textField.textrangeOfString:@"0"];
if(zeroRange.length==1&& zeroRange.location==0){//判断输入框第一个字符是否为“0”
if(![stringisEqualToString:@"0"] && ![stringisEqualToString:@"."] && [textField.textlength] ==1){//当输入框只有一个字符并且字符为“0”时,再输入不为“0”或者“.”的字符时,则将此输入替换输入框的这唯一字符。
textField.text= string;
returnNO;
}else{
if(pointRange.length==0&& pointRange.location>0){//当输入框第一个字符为“0”时,并且没有“.”字符时,如果当此输入的字符为“0”,则视当此输入无效。
if([stringisEqualToString:@"0"]){
returnNO;
}
}
}
}
NSString*buffer;
if( ![scannerscanCharactersFromSet:numbersintoString:&buffer] && ([stringlength] !=0) )
{
returnNO;
}
// 大于10亿的时候不能再编辑
if([tempStrlongLongValue] >=1000000000) {
returnNO;
}
}
if ([string isEqualToString:@"."]) {
if (range.location + 2 < textField.text.length) {
NSMutableString *notFormatString = [[NSMutableString alloc] initWithString:[textField.text substringWithRange:NSMakeRange(0, range.location + 2)]];
[notFormatString insertString:@"." atIndex:range.location];
textField.text = notFormatString;
return false;
}
}
return YES;
}
网友评论