UITextField adds a space every four digits

A project I did a few days ago has a recharge function for recharge cards. The recharge code entered in it requires a space to be added every four digits. I found a few on the Internet and finally found that there is a small problem, that is, when we use the Sogou input method to input, directly click and enter the associated words, the order will be confusing.

In order to solve this problem, I thought of a solution, which is to intercept the input characters in the proxy method of UITextField, and then re-edit it by ourselves. Finally, the test can perfectly solve this problem. The code is as follows

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

    // 删除字符直接替换拼接
    if ([string isEqualToString:@""]) {

        NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        textField.text = toBeString;

    } else {

        // 输入字符 首先拼接出输入之后的字符串
        NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        // 将所有输入的空格进行替换
        toBeString = [toBeString stringByReplacingOccurrencesOfString:@" " withString:@""];
        // 创建新的字符串用来存储自己重新排序的字符
        NSMutableString *strM = [NSMutableString string];
        // 获取单个字符并进行重新拼接 每四个字符插入一个空格
        NSInteger count = 0;
        for(int i = 0; i < [toBeString length]; i++) {
            count++;
            NSString *s = [toBeString substringWithRange:NSMakeRange(i, 1)];
            [strM appendString:s];
            if (count == 4) {
                [strM appendString:@" "];
                count = 0;
            }
        }
       // 将重新整理排序的字符直接赋值给textField
       textField.text = strM.copy;
    }

    // 此处一定返回NO 拦截系统的拼接执行
    return NO;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325981550&siteId=291194637