iOS textField輸入金額的限制,小數點前9位,后面兩位


iOS textField輸入金額的限制,小數點前9位,后面兩位,如果不加小數點,最大位數是9位,加上小數點,最大位數是12位,超出最大位數可刪除

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    // 判斷是否輸入內容,或者用戶點擊的是鍵盤的刪除按鈕

    if (![string isEqualToString:@""]) {

        NSCharacterSet *cs;

        if ([textField isEqual:countTextField]) {

            // 小數點在字符串中的位置 第一個數字從0位置開始

            NSInteger dotLocation = [textField.text rangeOfString:@"."].location;

            

            // 判斷字符串中是否有小數點,並且小數點不在第一位

            // NSNotFound 表示請求操作的某個內容或者item沒有發現,或者不存在

            // range.location 表示的是當前輸入的內容在整個字符串中的位置,位置編號從0開始

            if (dotLocation == NSNotFound && range.location != 0) {

                

                // 取只包含“myDotNumbers”中包含的內容,其余內容都被去掉

                /*

                 [NSCharacterSet characterSetWithCharactersInString:myDotNumbers]的作用是去掉"myDotNumbers"中包含的所有內容,只要字符串中有內容與"myDotNumbers"中的部分內容相同都會被舍去

                 

                 在上述方法的末尾加上invertedSet就會使作用顛倒,只取與“myDotNumbers”中內容相同的字符

                 */

                cs = [[NSCharacterSet characterSetWithCharactersInString:NumbersWithDot] invertedSet];

                if (range.location >= 9) {

                    NSLog(@"單筆金額不能超過億位");

                    if ([string isEqualToString:@"."] && range.location == 9) {

                        return YES;

                    }

                    

                    return NO;

                }

            }else {

                cs = [[NSCharacterSet characterSetWithCharactersInString:NumbersWithoutDot] invertedSet];

            }

            

            // 按cs分離出數組,數組按@""分離出字符串

            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

            BOOL basicTest = [string isEqualToString:filtered];

            if (!basicTest) {

                NSLog(@"只能輸入數字和小數點");

                return NO;

            }

            

            if (dotLocation != NSNotFound && range.location > dotLocation + 2) {

                NSLog(@"小數點后最多兩位");

                return NO;

            }

            

            if (textField.text.length > 11) {

                return NO;

            }

        }

    }

    

    return YES;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM