iOS textField输入限制小数点后两位
不废话,直接上代码!
由于不确定限制位数,设置moneyLength属性来记录位数,初始值最大integer值,可根据自己需求设置为相应位数!
moneyLength = NSIntegerMax;
textField协议:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (string.length == 0) { if([textField.text isEqualToString:@"¥0."]) { textField.text = @"¥"; return NO; } if(textField.text.length == 1)return NO; if(textField.text.length == NSIntegerMax)return YES; if ([textField.text hasSuffix:@"."]) { moneyLength = NSIntegerMax; return YES; } } NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容 if (([string isEqualToString:@"0"] && [toBeString isEqualToString:@"¥0"]) || ([string isEqualToString:@"."] && [toBeString isEqualToString:@"¥."])) { textField.text = @"¥0."; moneyLength = textField.text.length+2; return NO; } if ([string isEqualToString:@"."]) { if([textField.text containsString:@"."])return NO; moneyLength = toBeString.length + 2; return YES; } if ([toBeString length] > moneyLength-1) { if(textField.text.length == moneyLength) { // 可以做相应交互提示 return NO; } textField.text = [toBeString substringToIndex:moneyLength]; return NO; } return YES; }
这种方法适用复杂位数限定,若只有一种固定位数限制推荐下面一种方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if([textField.text isEqualToString:@"0."] && string.length == 0) { textField.text = @""; return NO; } NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容 if (([string isEqualToString:@"0"] || [string isEqualToString:@"."]) && textField.text.length == 0) { textField.text = @"0."; return NO; } if ([string isEqualToString:@"."] && [textField.text containsString:@"."])return NO; if ([textField.text containsString:@"."] && [toBeString componentsSeparatedByString:@"."].count > 1 && [toBeString componentsSeparatedByString:@"."].lastObject.length > 2) { return NO; } //设置为自己需要的位数(这里11位)
if ([toBeString containsString:@"."] ? toBeString.length > 10+3 : toBeString.length > 10) {
textField.text = [toBeString substringToIndex:[toBeString containsString:@"."] ?14:11];
return NO;
} return YES; }