Created
February 27, 2015 08:34
-
-
Save Eridana/036841bdaedabf6e2ab6 to your computer and use it in GitHub Desktop.
UITextField phone string format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_textField.delegate = self (UITextFieldDelegate) | |
- (NSMutableString *)filteredPhoneStringFromString:(NSString *)string withFilter:(NSString *)filter | |
{ | |
NSUInteger onOriginal = 0, onFilter = 0, onOutput = 0; | |
char outputString[([filter length])]; | |
BOOL done = NO; | |
while(onFilter < [filter length] && !done) | |
{ | |
char filterChar = [filter characterAtIndex:onFilter]; | |
char originalChar = onOriginal >= string.length ? '\0' : [string characterAtIndex:onOriginal]; | |
switch (filterChar) { | |
case '#': | |
if(originalChar=='\0') | |
{ | |
// We have no more input numbers for the filter. We're done. | |
done = YES; | |
break; | |
} | |
if(isdigit(originalChar)) | |
{ | |
outputString[onOutput] = originalChar; | |
onOriginal++; | |
onFilter++; | |
onOutput++; | |
} | |
else | |
{ | |
onOriginal++; | |
} | |
break; | |
default: | |
// Any other character will automatically be inserted for the user as they type (spaces, - etc..) or | |
// deleted as they delete if there are more numbers to come. | |
outputString[onOutput] = filterChar; | |
onOutput++; | |
onFilter++; | |
if(originalChar == filterChar) | |
onOriginal++; | |
break; | |
} | |
} | |
outputString[onOutput] = '\0'; // Cap the output string | |
return [[NSString stringWithUTF8String:outputString] copy]; | |
} | |
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { | |
NSString *filter = @"# (###) ### ## ##"; | |
if(!filter) return YES; // No filter provided, allow anything | |
NSString *changedString = [textField.text stringByReplacingCharactersInRange:range withString:string]; | |
if(range.length == 1 && // Only do for single deletes | |
string.length < range.length && | |
[[textField.text substringWithRange:range] rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]].location == NSNotFound) | |
{ | |
// Something was deleted. Delete past the previous number | |
NSInteger location = changedString.length-1; | |
if(location > 0) | |
{ | |
for(; location > 0; location--) | |
{ | |
if(isdigit([changedString characterAtIndex:location])) | |
{ | |
break; | |
} | |
} | |
changedString = [changedString substringToIndex:location]; | |
} | |
} | |
textField.text = [self filteredPhoneStringFromString:changedString withFilter:filter]; | |
return NO; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment