代碼功能:
//0.priceTextFiled.keyboardType = UIKeyboardTypeDecimalPad;//必須
//1.限制priceTextFiled只允許輸入正確的數額 比如 0 123 123. 123.0 123.12,不合法的: 00 0.1.23 將被過濾
//2.使用這種限制方法時,TextField不能允許移動光標(即:光標能且只能在最末尾),不能允許用戶使用粘貼進行輸入
//3.可以在TextField上蓋一層透明Button來達到2的要求
keycode:
[priceTextFiled.rac_textSignal subscribeNext:^(NSString *x) { static NSInteger const maxIntegerLength=8;//最大整數位 static NSInteger const maxFloatLength=2;//最大精確到小數位 if (x.length) { //第一個字符處理 //第一個字符為0,且長度>1時 if ([[x substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"0"]) { if (x.length>1) { if ([[x substringWithRange:NSMakeRange(1, 1)] isEqualToString:@"0"]) { //如果第二個字符還是0,即"00",則無效,改為"0" priceTextFiled.text=@"0"; }else if (![[x substringWithRange:NSMakeRange(1, 1)] isEqualToString:@"."]){ //如果第二個字符不是".",比如"03",清除首位的"0" priceTextFiled.text=[x substringFromIndex:1]; } } } //第一個字符為"."時,改為"0." else if ([[x substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"."]){ priceTextFiled.text=@"0."; } //2個以上字符的處理 NSRange pointRange = [x rangeOfString:@"."]; NSRange pointsRange = [x rangeOfString:@".."]; if (pointsRange.length>0) { //含有2個小數點 priceTextFiled.text=[x substringToIndex:x.length-1]; } else if (pointRange.length>0){ //含有1個小數點時,並且已經輸入了數字,則不能再次輸入小數點 if ((pointRange.location!=x.length-1) && ([[x substringFromIndex:x.length-1]isEqualToString:@"."])) { priceTextFiled.text=[x substringToIndex:x.length-1]; } if (pointRange.location+maxFloatLength<x.length) { //輸入位數超出精確度限制,進行截取 priceTextFiled.text=[x substringToIndex:pointRange.location+maxFloatLength+1]; } } else{ if (x.length>maxIntegerLength) { priceTextFiled.text=[x substringToIndex:maxIntegerLength]; } } } }];

