I'm trying to create a credit card processing view controller. I have a expiration date field that I would like to format as MM/YY on the fly.
I tried to follow the snippet from here UITextField format in xx-xx-xxx, but it uses NSNumber when used on a expiration date that has a leading 0 it doesn't work. I searched google and nothing came up either. The leading zero is removed. How can I use a UITextField to format as MM/YY on the fly as the user is inputing (ex. 05/16)?
It is possible because Stripe's UITextField for expiration date does do it in their library.
I'm not sure why I got down voted for a legitimate question, but I solved my problem so others can avoid asking it.
Your class needs to conform to the UITextFieldDelegate in order for this to work.
I created an action based on the UIControlEventEditingChanged event in the viewDidLoad function.
[dateUIText addTarget:self
action:@selector(dateTextFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
This is what the dateTextFieldDidChange function looks like when adding the "/" after the month:
- (void) dateTextFieldDidChange: (UITextField *)theTextField {
NSString *string = theTextField.text;
if (string.length == 2) {
theTextField.text = [string stringByAppendingString:@"/"];
} else if (string.length > 5) {
theTextField.text = [string substringToIndex:5];
}
}
When the user tries to backspace to make any adjustments to the month the function above won't allow it so this function is then needed to assist:
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([string isEqualToString:@""] && textField.text.length == 3) {
NSString *dateString = textField.text;
textField.text =
[dateString stringByReplacingOccurrencesOfString:@"/" withString:@""];
}
return YES;
}