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

來源:互聯網
上載者:User

標籤:

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;

}

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.