I have a UITextField that gets a credit card input. How can I automatically insert a dash after the user inputs a 4th character just like how the Groupon app for iOS does it when a user is typing his credit card number? Thanks in advance.
Asked
Active
Viewed 2,385 times
1
-
1This should help you: http://stackoverflow.com/a/6968689/5228 – Mariusz Nov 13 '12 at 09:24
2 Answers
0
This was harder that i thought.A common notification sent when the text changes is UITextFieldTextDidChangeNotification. In the viewDidLoad method you should register to receiver this notification and perform a selector when the text changes.In the selector you add a dash every 4 characters.
In my code the textfield is named textField.
- (void)viewDidLoad
{
[super viewDidLoad];
NSNotificationCenter* center=[NSNotificationCenter defaultCenter];
[center addObserver: self selector: @selector(textDidChange:) name: UITextFieldTextDidChangeNotification object: textField];
}
- (void) textDidChange : (NSNotification*) notification
{
NSString* string=[[textField text] stringByReplacingOccurrencesOfString: @"-" withString: @""];
__block NSMutableString* newString= [string mutableCopy];
NSMutableIndexSet* set=[NSMutableIndexSet new];
for(NSUInteger i=4; i<[string length];i+=4)
{
[set addIndex: i+i/4-1];
}
[set enumerateIndexesInRange: NSMakeRange(0, [string length]+[string length]/4) options: 0 usingBlock: ^(NSUInteger index, BOOL* stop)
{
[newString insertString: @"-" atIndex: index];
}];
[textField setText: newString];
}
The code to add a dash every 4 characters is long, maybe there's a shorter way to do it.
PS: The last version was incorrect, I edited it (wasn't able to delete characters properly).

Ramy Al Zuhouri
- 21,580
- 26
- 105
- 187
-
I found a bug in this code when running iOS 5. It hangs or freezes whenever the user types anything on the textField. Any recommendation for a fix? I'm assuming it's the block fault but I'm not sure. – jaytrixz Nov 28 '12 at 04:01
-
This could be simplified by implementing `UITextFieldDelegate`'s `textField:shouldChangeCharactersInRange:replacementString:` method. – Scott Berrevoets Nov 28 '12 at 07:17
-
0
This has worked excellently for me:
iOS automatically add hyphen in text field
Check the answer by "dingo sky".