Skip to content

Instantly share code, notes, and snippets.

@aug2uag
Last active January 1, 2016 21:29
Show Gist options
  • Save aug2uag/8203561 to your computer and use it in GitHub Desktop.
Save aug2uag/8203561 to your computer and use it in GitHub Desktop.
PseudoDateFormatter, custom UITextField input month/year expiration
#import "ViewController.h"
@interface ViewController () <UITextFieldDelegate>
@property (strong, nonatomic) UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat desiredFieldWidth = 100.0f;
_textField = [[UITextField alloc] initWithFrame:CGRectMake((self.view.bounds.size.width - desiredFieldWidth)/2, 110, desiredFieldWidth, 44)];
_textField.text = @"XX/YYYY";
_textField.delegate = self;
[self.view addSubview:_textField];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSArray* arrayString = [NSArray arrayWithArray:[self translateStringToArray:self.textField.text]];
NSLog(@"arrastring count = %i", arrayString.count);
NSLog(@"array string = %@", arrayString);
if (arrayString.count > 6) {
[[[UIAlertView alloc] initWithTitle:nil message:@"invalid input" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
_textField.text = @"XX/YYYY";
return NO;
}
if (arrayString.count == 0) {
_textField.text = @"XX/YYYY";
}
if (arrayString.count == 1) {
_textField.text = [NSString stringWithFormat:@"%@X/YYYY", arrayString[0]];
}
if (arrayString.count == 2) {
_textField.text = [NSString stringWithFormat:@"%@%@/YYYY", arrayString[0], arrayString[1]];
}
if (arrayString.count == 3) {
_textField.text = [NSString stringWithFormat:@"%@%@/%@YYY", arrayString[0], arrayString[1], arrayString[2]];
}
if (arrayString.count == 4) {
_textField.text = [NSString stringWithFormat:@"%@%@/%@%@YY", arrayString[0], arrayString[1], arrayString[2], arrayString[3]];
}
if (arrayString.count == 5) {
_textField.text = [NSString stringWithFormat:@"%@%@/%@%@%@Y", arrayString[0], arrayString[1], arrayString[2], arrayString[3], arrayString[4]];
}
if (arrayString.count == 6) {
_textField.text = [NSString stringWithFormat:@"%@%@/%@%@%@%@", arrayString[0], arrayString[1], arrayString[2], arrayString[3], arrayString[4], arrayString[5]];
}
return YES;
}
-(NSArray *)translateStringToArray:(NSString *)input
{
NSMutableArray *arr = [NSMutableArray array];
for (int i=0; i < input.length; i++) {
NSString *string = [input substringWithRange:NSMakeRange(i, 1)];
if ([[NSScanner scannerWithString:string] scanInt:nil]) {
NSLog(@"is integer");
[arr addObject:string];
} else {
NSLog(@"is not integer");
}
}
return arr;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment