1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
jaytrixz
  • 4,059
  • 7
  • 38
  • 57

2 Answers2

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
  • The problem is that I tested it on iOS 6, and it was working. – Ramy Al Zuhouri Dec 01 '12 at 14:20
0

This has worked excellently for me:

iOS automatically add hyphen in text field

Check the answer by "dingo sky".

Community
  • 1
  • 1
jaytrixz
  • 4,059
  • 7
  • 38
  • 57