iOS Objective-C UITextField 日期格式 [英] iOS Objective-C UITextField Date Formatting
问题描述
我正在尝试创建一个信用卡处理视图控制器.我有一个到期日期字段,我想即时将其格式化为 MM/YY.
我试图遵循这里的片段
我不知道为什么我对一个合法的问题投了反对票,但我解决了我的问题,这样其他人就可以避免问这个问题.
您的类需要符合 UITextFieldDelegate 才能使其正常工作.
我根据 viewDidLoad 函数中的 UIControlEventEditingChanged 事件创建了一个操作.
[dateUIText addTarget:self动作:@selector(dateTextFieldDidChange:)forControlEvents:UIControlEventEditingChanged];
这是 dateTextFieldDidChange 函数在月份后添加/"时的样子:
- (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];}}
当用户尝试退格对月份进行任何调整时,上面的功能将不允许这样做,因此需要此功能来提供帮助:
- (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:@""];}返回是;}
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;
}
这篇关于iOS Objective-C UITextField 日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!