Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

iOS Objective-C UITextField Date Formatting

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.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...