我必须输入字符串格式化为电话number.For我使用如何验证和格式的输入字符串1234567890至123-456-7890
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
if (string.length==3||string.length==7) {
filtered =[filtered stringByAppendingString:@"-"];
}
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}
这里
#define NUMBERS_ONLY @"1234567890-"
#define CHARACTER_LIMIT 12
,但它不是编辑回来。
请给一些想法
我不知道,你可以放心地忽略range.position,你做的方式。 –
更好的方法来实现相同的, http://stackoverflow.com/questions/7184094/how-to-use-phonenumberformatter-class-to-format-phone-number-in-uitextfield HTTP ://stackoverflow.com/questions/1246439/uitextfield-for-phone-number – satheeshwaran
请参阅我的答案在http://stackoverflow.com/questions/1246439/uitextfield-for-phone-number/35378246#35378246 – iphaaw