输入金额的需求
在UITextField中输入金额,我们需要判断输入金额的有效性,比如小数点后不能超过两位、金额需要大于等于1分、小数点只能出现一个等等,下面我就贴一下自己写的一个判断,希望可以帮助初学者
首先你需要让textfield遵循<UITextFieldDelegate>
在- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;方法中实现我们的判断
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//限制只能输入数字
BOOL isHaveDian = YES;
if ([string isEqualToString:@" "]) {
return NO;
}
if ([textField.text rangeOfString:@"."].location == NSNotFound) {
isHaveDian = NO;
}
if ([string length] > 0) {
unichar single = [string characterAtIndex:0];//当前输入的字符
if ((single >= '0' && single <= '9') || single == '.') {
//数据格式正确
if([textField.text length] == 0){
if(single == '.') {
[MBProgressHUD showError:@"请输入正确的价格"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
//输入的字符是否是小数点
if (single == '.') {
if(!isHaveDian) {
//text中还没有小数点
isHaveDian = YES;
return YES;
}else{
[MBProgressHUD showError:@"请输入正确的价格"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}else{
//存在小数点
if (isHaveDian) {
//判断小数点的位数
NSRange ran = [textField.text rangeOfString:@"."];
if (range.location - ran.location <= 2) {
return YES;
}else{
[MBProgressHUD showError:@"请输入正确的价格"];
return NO;
}
}else{
return YES;
}
}
}else{
//输入的数据格式不正确
[MBProgressHUD showError:@"请输入正确的价格"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
else
{
return YES;
}
}
希望简单的几句判断能帮助到您
网友评论