UITextField格式化电话号码和银行卡

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

NSString*text = [textFieldtext];

NSCharacterSet*characterSet = [NSCharacterSetcharacterSetWithCharactersInString:@"0123456789\b"];

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

if([stringrangeOfCharacterFromSet:[characterSetinvertedSet]].location!=NSNotFound) {

returnNO;

}

text = [textstringByReplacingCharactersInRange:rangewithString:string];

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

// 如果是电话号码格式化,需要添加这三行代码

NSMutableString*temString = [NSMutableStringstringWithString:text];

[temStringinsertString:@" "atIndex:0];

text = temString;

NSString*newString =@"";

while(text.length>0) {

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

newString = [newStringstringByAppendingString:subString];

if(subString.length==4) {

newString = [newStringstringByAppendingString:@" "];

}

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

}

newString = [newStringstringByTrimmingCharactersInSet:[characterSetinvertedSet]];

if(newString.length>=14) {

returnNO;

}

[textFieldsetText:newString];

returnNO;

}

这段代码是极好的:不但一个个输入字符时没有问题,而且可以实现,复制粘贴过来后再实现格式化

你可能感兴趣的:(UITextField格式化电话号码和银行卡)