在文本字段中仅键入日期

时间:2013-02-11 07:37:38

标签: objective-c xcode nsstring

有没有办法确保用户只能在文本字段中输入日期?例如,字符0-9和/(或更好的解决方案)?如果是这样,最好的方法是什么?

我没有成功

  

NSString * LEGAL = @“0123456789 /”;

     

NSCharacterSet * characterSet = [[NSCharacterSet   characterSetWithCharactersInString:LEGAL] invertedSet];

     

NSString * filteredOne = [[firstString   componentsSeparatedByCharactersInSet:CHARACTERSET]

     

componentsJoinedByString:@ “”];

     

NSString * filteredTwo = [[secondString   componentsSeparatedByCharactersInSet:CHARACTERSET]

     

componentsJoinedByString:@ “”];

     

firstString = filteredOne;

     

secondString = filteredTwo;

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,我可以提供帮助。以下是我之前使用的一些旧代码,用于格式化文本字段以选择日期。希望您能够理解它并使其适应您的需求:

注意:UITextField *endDate;

 //Get date and format it for the textfields
-(void)updateTextField:(id)sender
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];

    UIDatePicker *picker = (UIDatePicker*)self.endDate.inputView;
    NSString *theDate = [dateFormat stringFromDate:picker.date];

    self.endDate.text = [NSString stringWithFormat:@"%@",theDate];

    [dateFormat release];
}

要使用日期选择器而不是键盘,请在viewDidLoad()方法中尝试这样的事情*

//Make date pickers instead of keyboards for time text boxes
UIDatePicker *datePicker = [[[UIDatePicker alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 162.0)] autorelease];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.maximumDate = [NSDate date];
NSDate *setDate = [NSDate dateWithYear: 2012 month: 02 day: 03];
[datePicker setDate:setDate];
[datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];       
[self.startDate setInputView:datePicker];

datePicker = [[[UIDatePicker alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 162.0)] autorelease];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.maximumDate = [NSDate date];
setDate = [NSDate dateWithYear: 2012 month: 02 day: 10];
[datePicker setDate:setDate];
[datePicker addTarget:self action:@selector(updateTextField2:) forControlEvents:UIControlEventValueChanged];       
[self.endDate setInputView:datePicker];

*注意,您可能需要自己的NSDate接口/实现,如果是这样,代码如下。不要忘记将其导入文件顶部!

NSDate.h

#import <Foundation/Foundation.h>

@interface NSDate (missingFunctions) 
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;
@end

NSDate.m

#import "NSDate.h"

@implementation NSDate (missingFunctions)

+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    return [calendar dateFromComponents:components];
}   
@end