我必須輸入字符串格式化爲電話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