textFiled格式化输入 4位字符一个空格

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

{

    NSString *text = [textField text];

    NSCharacterSet *character = [NSCharacterSet characterSetWithCharactersInString:@"1234567890qwertyuioplkjhgfdsazxcvbnm\b"];

    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];

    if ([string rangeOfCharacterFromSet:[character invertedSet]].location != NSNotFound) {

        return NO;

    }

    text = [text stringByReplacingCharactersInRange:range withString:string];

    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSString *newString = @"";

    while (text.length > 0) {

        NSString *subString = [text substringToIndex:MIN(text.length, 4)];

        newString = [newString stringByAppendingString:subString];

        if (subString.length == 4) {

            newString = [newString stringByAppendingString:@" "];

        }

        text = [text substringFromIndex:MIN(text.length, 4)];

    }

    newString = [newString stringByTrimmingCharactersInSet:[character invertedSet]];

    [textField setText:newString];

    return NO;

}

 

posted @ 2016-03-08 11:40  xiaolingling  阅读(259)  评论(0编辑  收藏  举报