回答がバックスペースを本当にうまく処理しません。ここに私の解決策は、(残念ながらObjective-Cで実装されている)だ:Jigarの答え@に基づいて
@interface CreditCardViewController()
<UITextFieldDelegate>
@property (weak,nonatomic) IBOutlet UITextField * cardExpirationTextField;
@property (strong,nonatomic) NSString * previousExpiryDate;
@property (strong,nonatomic) UITextRange * previousExpiryDateSelection;
@property (assign,readonly,nonatomic) NSString * minYearLast2Digits;
@end
@implementation CreditCardViewController
-(instancetype) init
{
self = [super initWithNibName:NSStringFromClass([CreditCardViewController class]) bundle:nil];
if(self){
_minYearLast2Digits = [[[NSNumber numberWithInteger:[NSDate date].year] stringValue] substringFromIndex:2];
}
return self;
}
-(void) viewDidLoad
{
[super viewDidLoad];
[self setupView]
}
-(void) setupView
{
self.cardExpirationTextField.delegate = self;
[self.cardExpirationTextField addTarget:self
action:@selector(reformatCardExpiryDate:)
forControlEvents:UIControlEventEditingChanged];
}
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [textField.text length] + [string length] - range.length;
if(textField == self.cardExpirationTextField){
self.previousExpiryDate = textField.text;
self.previousExpiryDateSelection = textField.selectedTextRange;
return newLength <= 5;
}
return YES;
}
-(void) reformatCardExpiryDate:(UITextField*) textField
{
const BOOL isErasing = self.previousExpiryDate.length > textField.text.length;
BOOL invalid = [textField.text length] > 5;
if([textField.text length] > 0){
unichar firstChar = [textField.text characterAtIndex:0];
invalid |= (firstChar > '1');
}
if([textField.text length] > 1){
unichar firstChar = [textField.text characterAtIndex:0];
unichar secondChar = [textField.text characterAtIndex:1];
invalid |= (firstChar == '1' && secondChar > '2');
}
if([textField.text length] > 2){
invalid |= [textField.text characterAtIndex:2] != '/';
}
if([textField.text length] > 3){
unichar yearFirstDigit = [textField.text characterAtIndex:3];
unichar minYearFirstDigit = [self.minYearLast2Digits characterAtIndex:0];
invalid |= yearFirstDigit < minYearFirstDigit;
}
if([textField.text length] > 4){
NSString* yearLastTwoDigits = [textField.text substringFromIndex:3];
invalid |= [yearLastTwoDigits compare:_minYearLast2Digits] == NSOrderedAscending;
}
if(invalid){
[textField setText:self.previousExpiryDate];
textField.selectedTextRange = self.previousExpiryDateSelection;
return;
}
if(!isErasing && textField.text.length == 2){
textField.text = [textField.text stringByAppendingString:@"/"];
UITextPosition *targetPosition =
[textField positionFromPosition:[textField beginningOfDocument]
offset:textField.text.length];
[textField setSelectedTextRange:
[textField textRangeFromPosition:targetPosition
toPosition:targetPosition]
];
}
}
@end
使用これを:http://stackoverflow.com/questions/7709450/uitextfield-format-in-xx-xx-xxx – Vickyexpert